How a Java Web Request Travels Through a Spring Boot Application

Spring Boot has become the dominant framework for building Java web applications, but many developers use it without understanding the journey a request takes from the browser to your code and back. This end-to-end explanation will demystify this process, helping you debug issues, improve performance, and write better code.

The Journey Begins: Client Request

  1. Browser Initiates HTTP Request

    • User clicks a link, submits a form, or your JavaScript code calls fetch()
    • Browser formulates an HTTP request with:
      • Method (GET, POST, PUT, DELETE)
      • URL (/api/users)
      • Headers (Content-Type, Authorization)
      • Optional body (for POST/PUT requests)
  2. Network Travel

    • Request travels through the internet to your server
    • Passes through firewalls, load balancers, and proxy servers
    • Eventually reaches your application server

The Server Entry Point

  1. Web Server Receives the Request

    • Spring Boot typically embeds Tomcat (but can use Jetty or Undertow)
    • The server listens on a port (default: 8080)
    • Parses raw HTTP into a ServletRequest object
    • Creates a thread from its thread pool to process the request
  2. The Servlet Container

    • The foundation of Java web applications
    • Manages the request/response lifecycle
    • Routes the request to the appropriate servlet
  3. DispatcherServlet - Spring’s Front Controller

    • The central entry point for all Spring MVC applications
    • Registered as a servlet in your application
    • Implements the “Front Controller” design pattern
    • Coordinates the entire request handling process

Security and Pre-Processing

  1. Filter Chain Processing

    • Filters intercept every request before reaching your code
    • Implement the javax.servlet.Filter interface
    • Execute in a specific order
    • Common filter use cases:
      • Authentication (verifying user identity)
      • Authorization (checking permissions)
      • CORS handling
      • Request logging
      • Compression
    public class RequestLoggingFilter implements Filter {
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
            HttpServletRequest req = (HttpServletRequest) request;
            log.info("Request received: {} {}", req.getMethod(), req.getRequestURI());
            // Pass to the next filter or to the servlet
            chain.doFilter(request, response);
        }
    }
  2. Spring Security (If Configured)

    • Implemented as a series of filters
    • Validates authentication tokens or session cookies
    • Checks authorization for protected endpoints
    • Can reject the request before it reaches your controller

Request Routing and Controller Selection

  1. Handler Mapping

    • DispatcherServlet uses a HandlerMapping to find the right controller
    • Matches URL patterns against controller mappings
    • For example, /api/users might map to UserController.getUsers()
    • Also considers HTTP method and request parameters
  2. Handler Interceptors

    • Similar to filters but Spring-specific
    • Run before and after controller execution
    • Implement HandlerInterceptor interface
    • Common uses:
      • Measuring execution time
      • Checking permissions specific to certain controller groups
      • Preparing resources needed by controllers
    public class PerformanceInterceptor implements HandlerInterceptor {
        public boolean preHandle(HttpServletRequest request, ...) {
            request.setAttribute("startTime", System.currentTimeMillis());
            return true; // Continue processing
        }
        
        public void postHandle(HttpServletRequest request, ...) {
            long startTime = (Long) request.getAttribute("startTime");
            log.info("Request took {} ms", System.currentTimeMillis() - startTime);
        }
    }

Controller Execution

  1. Handler Adapter & Parameter Resolution

    • Adapts the HTTP request to your controller method
    • Resolves method parameters from different sources:
      • Path variables (@PathVariable)
      • Query parameters (@RequestParam)
      • Form data
      • Request body (@RequestBody)
      • Headers (@RequestHeader)
  2. Controller Method Execution

    • Your @RestController or @Controller method runs
    • Receives the resolved parameters
    • Executes business logic
    • Returns a response (object, view name, or ResponseEntity)
    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        private final UserService userService;
        
        @GetMapping
        public List<User> getUsers() {
            // This is the actual code you wrote
            return userService.findAllUsers();
        }
    }

The Service Layer

  1. Service Method Execution

    • Controllers delegate business logic to service classes
    • Services contain the core application logic
    • May involve transaction management (@Transactional)
    • May call multiple repositories
    @Service
    public class UserService {
        private final UserRepository userRepository;
        
        @Transactional(readOnly = true)
        public List<User> findAllUsers() {
            return userRepository.findAll();
        }
    }

Data Access

  1. Repository Layer

    • Interacts with the database
    • Often uses Spring Data interfaces like JpaRepository
    • Translates method calls into database operations
    public interface UserRepository extends JpaRepository<User, Long> {
        // Spring automatically implements this
        List<User> findByActiveTrue();
    }
  2. Database Interaction

    • Hibernate (JPA implementation) converts repository calls to SQL
    • Connection pooling manages database connections
    • SQL is executed against the database
    • Result sets are mapped back to Java objects
    • Entities are cached if configured

Response Generation

  1. Controller Return Value Handling

    • Controller method returns data
    • Return value is processed by ReturnValueHandler
    • For @RestController, converts objects to JSON/XML
    • For @Controller, might render a view template
  2. Message Conversion

    • HttpMessageConverter takes your Java objects
    • Converts them to the requested format (typically JSON)
    • Jackson library (default) handles the serialization
    • Content-Type headers determine the format
  3. Post-Processing

    • Interceptor postHandle methods run
    • Filters process the response in reverse order
    • Can modify headers or the response body

Response Return

  1. Response Completion
    • Servlet container assembles the HTTP response
    • Headers and body are combined
    • Sent back through the network to the client
    • Browser receives and processes the response
NOTE: The content below is additional technical knowledge and not necessary for basic understanding. Feel free to stop here if you're looking for just the essential process.

Technical Deep Dive

Spring Boot’s Auto-Configuration Magic

Spring Boot’s auto-configuration is what makes it so easy to use:

  1. @SpringBootApplication

    • Combines three annotations:
      • @Configuration: Marks the class as a source of bean definitions
      • @EnableAutoConfiguration: Enables auto-configuration
      • @ComponentScan: Scans for components in the package
  2. Conditional Configuration

    • Uses @ConditionalOnClass, @ConditionalOnBean, etc.
    • Only applies configuration when specific conditions are met
    • This is how Spring Boot “just works” with minimal setup

The Servlet API Hierarchy

Understanding the Servlet API helps with debugging:

  1. ServletContext

    • Represents the entire web application
    • Shared across all requests and servlets
    • Access to application-wide information
  2. ServletRequest/ServletResponse

    • Basic interfaces for HTTP communication
    • Extended by HttpServletRequest/HttpServletResponse
    • Provide access to parameters, headers, cookies, etc.
  3. Filter Chain

    • Linked list of filters plus the target servlet
    • Each filter must call chain.doFilter() to continue
    • Can short-circuit the request by not calling the chain

Spring MVC Components in Detail

The components that power Spring MVC:

  1. HandlerMapping Strategies

    • RequestMappingHandlerMapping: Maps @RequestMapping annotations
    • SimpleUrlHandlerMapping: Maps URLs to handlers directly
    • BeanNameUrlHandlerMapping: Maps URLs to bean names
  2. HandlerAdapter Types

    • RequestMappingHandlerAdapter: For @RequestMapping methods
    • HttpRequestHandlerAdapter: For HttpRequestHandler implementations
    • SimpleControllerHandlerAdapter: For Controller interface
  3. ViewResolver Chain

    • Converts view names to actual View implementations
    • Examples: ThymeleafViewResolver, FreeMarkerViewResolver
    • Can have multiple resolvers with different priorities

Exception Handling Flow

When things go wrong:

  1. Controller-Level Exception Handling

    • @ExceptionHandler methods in controllers
    • Handle exceptions thrown within that controller
  2. Global Exception Handling

    • @ControllerAdvice classes
    • Apply exception handling across multiple controllers
    • Can target specific exception types or packages
  3. Default Error Handling

    • Spring Boot’s /error endpoint
    • Customizable via ErrorController implementation

Performance Considerations

Key areas that affect performance:

  1. Thread Pool Configuration

    • Too few threads: Requests queue up
    • Too many threads: Excessive context switching
    • Tomcat default: max 200 threads
  2. Connection Pooling

    • HikariCP (Spring Boot default)
    • Manages database connections
    • Proper sizing prevents connection wait times
  3. Caching Strategies

    • HTTP caching (ETag, Cache-Control headers)
    • Spring’s @Cacheable for method results
    • Hibernate’s entity cache and query cache

Security Implementation Details

How Spring Security works internally:

  1. SecurityFilterChain

    • Series of specialized filters
    • Each handles a specific security concern
    • Examples: AuthenticationFilter, AuthorizationFilter, CsrfFilter
  2. Authentication Manager

    • Coordinates authentication providers
    • Each provider handles different auth methods
    • Examples: JDBC, LDAP, OAuth2
  3. Security Contexts

    • ThreadLocal storage of authenticated user
    • SecurityContextHolder provides access
    • Propagated between threads when needed

Conclusion

Understanding the complete request lifecycle in a Spring Boot application gives you deeper insight into how your code interacts with the framework. This knowledge is invaluable when debugging issues, optimizing performance, or extending the framework’s capabilities.

The beauty of Spring Boot is that it handles all this complexity while allowing you to focus on writing your business logic. But when issues arise, knowing what happens under the hood makes all the difference in resolving them quickly and effectively.