Foundation · Build

The DispatcherServlet

One servlet fronts every request: DispatcherServlet consults HandlerMappings, invokes the handler through a HandlerAdapter, and hands the result to converters or view resolvers.

Primary source: Spring MVC: DispatcherServlet

20 min

Lesson 2 of 11

1d streak

The Architectural Question

Debugging 404s, wrong converters, or surprise interceptor order requires knowing the dispatch pipeline the request actually travels through.

What this guide proves

  • Front Controller
  • HandlerMapping
  • HandlerAdapter

DispatcherServlet.doDispatch(): The heart of Spring MVC

Every request in Spring MVC passes through DispatcherServlet.doDispatch(). Understanding this method eliminates all mystery behind web requests.

  1. 011. Check Multipart: If multipart/form-data, wrap request in MultipartHttpServletRequest.
  2. 022. Determine Handler: Query HandlerMapping list to find HandlerExecutionChain (controller method + interceptors).
  3. 033. Determine Adapter: Locate HandlerAdapter capable of executing the handler (RequestMappingHandlerAdapter).
  4. 044. Apply Pre-Interceptors: Execute HandlerInterceptor.preHandle() in order.
  5. 055. Execute Handler: HandlerAdapter invokes the controller method with resolved arguments.
  6. 066. Apply Post-Interceptors: Execute HandlerInterceptor.postHandle().
  7. 077. Process Dispatch Result: Handle exceptions or render view, followed by triggerAfterCompletion() cleanup.
CustomInterceptor.java
@Component
public class CorrelationIdInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        String correlationId = Optional.ofNullable(req.getHeader("X-Correlation-ID"))
            .orElseGet(() -> UUID.randomUUID().toString());
        MDC.put("correlationId", correlationId);
        res.setHeader("X-Correlation-ID", correlationId);
        return true; // Continue dispatch pipeline!
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
        MDC.remove("correlationId");
    }
}

HandlerInterceptor: Filter vs Interceptor boundaries

Architectural Boundary · Do Not Confuse

Concept A

Servlet Filter (Tomcat Level)

Concept B

HandlerInterceptor (Spring MVC Level)

Filters run outside DispatcherServlet at the servlet container boundary. They cannot access Spring handler methods. Interceptors run inside DispatcherServlet, having direct access to the target HandlerMethod object, allowing inspection of controller annotations.

Break it deliberately: Returning false from preHandle without writing response

If a HandlerInterceptor.preHandle() method returns false (to reject a request) but forgets to set a status code or write to the response, the client receives an empty 200 OK with no body!

The Golden Rule of Interceptors

Whenever preHandle() returns false, you MUST write the HTTP status code (e.g. response.sendError(401)) or send a ProblemDetail payload to close the response.

Check your understanding

Active Recall Checkpoint

What is the core execution method in DispatcherServlet that orchestrates handler mapping, adapter execution, and interceptor hooks?

Hint: The central method name.

Show answer & explanation

DispatcherServlet.doDispatch() is the core method that drives the entire HTTP request lifecycle in Spring MVC.

Active Recall Checkpoint

How does a Servlet Filter differ from a Spring HandlerInterceptor in terms of container boundary?

Hint: Does it run before or after DispatcherServlet?

Show answer & explanation

A Servlet Filter runs at the servlet container (Tomcat) level before DispatcherServlet is reached. A HandlerInterceptor runs inside DispatcherServlet with access to the target Spring HandlerMethod.

Runtime Architecture & Flow

Spring MVC request lifecycle

DispatcherServlet coordinates the HTTP boundary

The controller is only one stop. Spring selects it, prepares its arguments, invokes it, and converts its return value.

Inbound request
Outbound response

Phase 1 of 6

Servlet filters inspect raw HTTP

Transport concerns such as correlation IDs or security can run before Spring MVC chooses a controller.

Synthesis & Production Verification

Production Acceptance Criteria

  • Explain the front controller pattern in Spring MVC terms
  • Name what HandlerMapping and HandlerAdapter each contribute to dispatch
  • Trace one request through doDispatch with breakpoints

Architectural & Technical Review

Core Interview Questions

Q01What do HandlerMapping and HandlerAdapter each do?Show answer

HandlerMapping selects a handler plus interceptors for the request. HandlerAdapter knows how to invoke that handler, including argument resolution and return-value handling.

Q02How can you prove whether a controller route was registered?Show answer

Inspect RequestMappingHandlerMapping handler methods, secured mapping diagnostics, or MVC tests rather than inferring registration from server startup.

Q03Why does a 415 response point away from route discovery?Show answer

It means the request representation is unsupported for the selected processing path. Inspect Content-Type, consumes conditions, and HttpMessageConverter readers.

Production Pitfalls

Critical Anti-Patterns

  • Pitfall: Treating DispatcherServlet as one monolithic router — The servlet coordinates mappings, adapters, converters, and exception resolvers; each produces different diagnostic evidence.
  • Pitfall: Debugging every 4xx as a bad URL — 405, 406, 415, and binding-related 400 responses prove different stages and require different inspections.

Primary Documentation & Specifications

Lesson Primary References

Supplementary Module Resources