Skip to content
javahacks.dev
Spring MVC

Spring DispatcherServlet Explained Through One Request

Follow one HTTP request through the Spring MVC DispatcherServlet: handler mapping, interceptors, arguments, message conversion and exceptions.

5 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring, Apache Maven, Swagger and Spring Boot logos.

Every Spring MVC application has one servlet that receives all the requests: the DispatcherServlet. It does no application work itself. It is a front controller that looks up who should handle a request, calls them, and turns the result into a response. Knowing its steps explains where each of the exceptions, filters and annotations lives, and why a given error happens before or after your controller. This post follows one request through the servlet on Spring Framework 7 and Spring Boot 4, then maps common errors to the step that produces them.

The request, step by step

Take GET /orders/42 handled by this method:

src/main/java/com/example/web/OrderController.javajava
@RestController
@RequestMapping("/orders")
class OrderController {

    @GetMapping("/{id}")
    OrderView get(@PathVariable long id, @RequestParam(defaultValue = "false") boolean full) {
        return service.view(id, full);
    }
}

The servlet container (Tomcat, Jetty or Undertow) receives the bytes, builds an HttpServletRequest, and passes it through the filter chain. Filters such as the security chain, character encoding and CORS run here, before Spring MVC knows anything about the request. A request rejected by a filter never reaches the DispatcherServlet, so the controller advice cannot handle it.

Then DispatcherServlet.doDispatch takes over, in this sequence.

1. Find the handler. It asks each HandlerMapping bean, in order, for a handler for this request. RequestMappingHandlerMapping holds the table built at startup from every @RequestMapping and its variants, and matches by path pattern, HTTP method, Content-Type, Accept, parameters and headers. It returns a HandlerExecutionChain: the handler method plus the interceptors that apply. No match produces a 404 (a NoResourceFoundException or NoHandlerFoundException); a path match with the wrong method produces a 405, described in 405 Method Not Allowed.

**2. Run the interceptors' preHandle.** Each HandlerInterceptor registered through WebMvcConfigurer gets a chance to stop the request or add to it. Interceptors are MVC-level: they know the handler, which filters do not.

3. Call the handler through an adapter. RequestMappingHandlerAdapter invokes the method. Before the call, HandlerMethodArgumentResolvers create each argument: @PathVariable pulls 42 from the URI and converts it to long, @RequestParam reads the query string and applies the default, @RequestBody reads the body through an HttpMessageConverter, Principal and HttpServletRequest are injected. A failed conversion or a missing required parameter throws here, for example MissingServletRequestParameterException, and a malformed body throws HttpMessageNotReadableException. These happen before your method body runs.

4. The controller method runs. Your code, with its exceptions.

5. Handle the return value. A HandlerMethodReturnValueHandler takes OrderView. For a @RestController the handler for @ResponseBody chooses an HttpMessageConverter using the Accept header (Jackson for JSON) and writes the body. For a @Controller returning a string, the value is a view name, resolved by a ViewResolver and rendered by a template engine. A client that asks for a media type nothing can produce gets 406, and a body type nothing can read gets 415; see unsupported media types.

**6. Run postHandle and afterCompletion** on the interceptors, in reverse order. afterCompletion always runs when preHandle returned true, even after an exception, so it is the place for cleanup.

7. Exceptions. Any exception from steps 1 to 6 goes to the HandlerExceptionResolver beans. ExceptionHandlerExceptionResolver finds a matching @ExceptionHandler, in the controller or in a @ControllerAdvice; ResponseStatusExceptionResolver handles @ResponseStatus; DefaultHandlerExceptionResolver maps Spring's own exceptions to 4xx statuses. If nobody handles it, the exception propagates to the container, which produces the error page, and in Boot the /error mapping renders the JSON or the Whitelabel page, see the Whitelabel error page. Writing your own handler is covered in global exception handlers.

Finally the response travels back out through the filters, in reverse order.

Watch it happen

You do not have to take any of this on trust. Turn on the logging for the web package and make one request:

properties
logging.level.org.springframework.web=DEBUG
logging.level.org.springframework.web.servlet.DispatcherServlet=TRACE
Text
DEBUG DispatcherServlet : GET "/orders/42?full=true", parameters={masked}
DEBUG RequestMappingHandlerMapping : Mapped to com.example.web.OrderController#get(long, boolean)
DEBUG HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json]
DEBUG DispatcherServlet : Completed 200 OK

The lines map to the steps: the mapping found, the converter picked, the completion status. When a request misbehaves, the third line is often the answer: which handler was chosen, or that none was. TRACE adds the parameters, and logging.level.org.springframework.web.servlet.mvc.method.annotation=TRACE the argument resolution. Parameters are masked at DEBUG unless you set spring.mvc.log-request-details=true, which you should do only in development since it logs headers and form data.

Where common errors come from

SymptomStep
404 for an existing path1, no mapping matched: wrong prefix, wrong method, component not scanned
405 with an Allow header1, path matched but not the method
400 on a missing parameter3, argument resolution
400 HttpMessageNotReadableException3, body conversion, see JSON parse errors
415 or 4063 or 5, media type negotiation
401 or 403 before any controller codeFilters, the security chain
@ControllerAdvice not calledThe exception came from a filter, or was thrown after the response committed
Controller advice called for a Spring exception onlyYour handler type is too narrow

Missing required parameters are covered in MissingServletRequestParameterException.

Where to put what

Put cross-cutting concerns at the layer that has the information they need. Authentication, CORS, compression and request ids go in filters, because they apply to every request including static resources and need nothing from MVC. Per-handler concerns that need the handler, such as timing a controller method or checking an annotation on it, go in interceptors. Business rules do not belong in either; they belong in services. Formatting of errors goes in controller advice. A rule of thumb: if you reach for request.getAttribute to pass data between a filter and a controller, check whether an interceptor or argument resolver would be the cleaner place.

Multiple dispatchers and path matching

An application can register more than one DispatcherServlet, each with its own context and its own mapping, for example one for the public site and one for an internal API. In Spring Boot, the auto-configured servlet is mapped to /, and an additional servlet is registered through a ServletRegistrationBean with a distinct path. Path matching uses PathPatternParser by default, which is stricter and faster than the older Ant matcher: a trailing slash no longer matches by default, so /orders and /orders/ are different routes unless you configure otherwise. Keep that in mind when a client that worked on one version gets a 404 on another.

Where this does not apply

WebFlux has no DispatcherServlet. It has an equivalent, DispatcherHandler, with the same ideas in reactive form. The servlet is replaceable and configurable: you can register more than one, for example for an API under /api and an admin console, each with its own context. The reference is the DispatcherServlet chapter, the Javadoc, and the walk-through of building an API in the Spring MVC REST guide. The relationship to filters is explored in how Spring MVC handles a request.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.