How Spring MVC Handles a Request From Filter to View
Follow one HTTP request through filters, the DispatcherServlet, handler mapping, argument resolution, the controller and the response writer.

You send GET /orders/7 to a Spring Boot application and get JSON back in a few milliseconds. In between, at least eight components looked at that request, and every Spring MVC error message you will ever meet is one of them complaining. A 405 is the handler mapping saying the path matched but not the method. A 400 with HttpMessageNotReadableException is the argument resolver failing to read the body. A white page with a status line is the error dispatch. Knowing the route lets you find where a request died by reading the stack trace, instead of guessing. This post follows one request from the servlet container's filter chain to the written response, with a working controller, a filter, an interceptor and an exception handler, and a log setting that shows each decision. Examples use Spring Boot 4, Spring Framework 7 and Tomcat 11.
The route of one request
Here is the sequence for a request that reaches a @RestController, in the order things happen:
| Step | Component | Question it answers |
|---|---|---|
| 1 | Servlet container (Tomcat) | Parse HTTP into a HttpServletRequest |
| 2 | Filter chain | Should this request continue at all? (security, encoding, logging) |
| 3 | DispatcherServlet | The front controller; coordinates everything below |
| 4 | HandlerMapping | Which controller method serves this URL, method and headers? |
| 5 | HandlerInterceptor.preHandle | Does anything need to stop it before the method? |
| 6 | HandlerAdapter and argument resolvers | Build the method's arguments from the request |
| 7 | Your controller method | The only step you wrote |
| 8 | Return value handlers and message converters | Turn the result into response bytes |
| 9 | Interceptor afterCompletion, filters unwind | Cleanup, and the response leaves |
Everything in one box below the controller is Spring's, and each can be replaced. The single controller below is enough to walk through all of it.
package dev.javahacks.web;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) {
this.orders = orders;
}
@GetMapping("/{id}")
OrderResponse get(@PathVariable long id, @RequestParam(defaultValue = "false") boolean expand) {
return orders.find(id, expand);
}
@PostMapping
ResponseEntity<OrderResponse> create(@RequestBody @Valid CreateOrder request) {
return ResponseEntity.status(201).body(orders.create(request));
}
}Filters run first
A filter belongs to the servlet specification, not to Spring MVC. It runs before DispatcherServlet and sees every request, including ones that never match a controller, such as a request for a missing static file. Spring Security is a filter chain, which is why an unauthenticated request gets a 401 without any controller being involved.
package dev.javahacks.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
class TimingFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(TimingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
long start = System.nanoTime();
try {
chain.doFilter(request, response); // everything below happens in here
} finally {
log.info("{} {} -> {} in {} ms", request.getMethod(), request.getRequestURI(),
response.getStatus(), (System.nanoTime() - start) / 1_000_000);
}
}
}INFO TimingFilter : GET /orders/7 -> 200 in 14 msThe try/finally around chain.doFilter is the shape of every filter: code before the call runs on the way in, code after runs on the way out, and not calling the chain stops the request. The order among filters is set with @Order or a FilterRegistrationBean.
The front controller picks a handler
DispatcherServlet is the one servlet Spring MVC registers. Its job is to ask each HandlerMapping bean, in order, whether it can serve the request. RequestMappingHandlerMapping is the one that reads your @GetMapping and @PostMapping annotations at startup and keeps a table of every mapping. It matches on path, HTTP method, Content-Type (the consumes attribute), Accept (produces), parameters and headers, and picks the most specific match.
The table is what produces the common routing errors. A path that matches but whose method does not is a 405 Method Not Allowed, explained in fixing 405 in Spring MVC. A path no mapping knows falls through to the resource handler for static files, and then to a 404; Boot renders that as the page covered in the Whitelabel error page. To see the table, turn on the mapping log:
logging:
level:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping: trace
org.springframework.web.servlet.DispatcherServlet: debugRequestMappingHandlerMapping : Mapped to dev.javahacks.web.OrderController#get(long, boolean)
DispatcherServlet : GET "/orders/7", parameters={}The framework that builds this machinery from your beans is the container described in how the Spring container really works.
Interceptors wrap the handler
A HandlerInterceptor sits between the dispatcher and the controller and, unlike a filter, knows which handler was chosen. It has three hooks: preHandle runs before the method and can return false to stop, postHandle runs after the method but before the response is written, and afterCompletion always runs at the end, even after an exception.
@Component
class AuditInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod hm) {
request.setAttribute("audit.action", hm.getMethod().getName());
}
return true;
}
}@Configuration
class WebConfig implements WebMvcConfigurer {
private final AuditInterceptor audit;
WebConfig(AuditInterceptor audit) {
this.audit = audit;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(audit).addPathPatterns("/orders/**");
}
}Reach for a filter when the concern applies to all requests or must run before Spring (security, request IDs, compression). Reach for an interceptor when you need to know the handler method or you only care about MVC-mapped paths.
The adapter builds the arguments
Once the handler is chosen, a HandlerAdapter (for annotated methods, RequestMappingHandlerAdapter) calls it. For each parameter it asks a chain of argument resolvers to produce a value, based on the annotations:
| Parameter | Resolver | Failure when it cannot |
|---|---|---|
@PathVariable long id | Reads the URI template, converts to long | MethodArgumentTypeMismatchException (400) for /orders/abc |
@RequestParam boolean expand | Reads the query string, applies the default | MissingServletRequestParameterException if required and absent |
@RequestBody CreateOrder | Picks a message converter by Content-Type, reads the body | HttpMessageNotReadableException for bad JSON |
@Valid on the body | Runs Bean Validation on the result | MethodArgumentNotValidException (400) |
Each failure maps to a specific message you can recognize: a missing parameter is the subject of MissingServletRequestParameterException, a body that does not parse is HttpMessageNotReadableException, and a failed validation is MethodArgumentNotValidException. They all happen before your method body runs, so if your code never prints, look here first.
The return value becomes a response
Your method returned an OrderResponse. A HandlerMethodReturnValueHandler takes it from there. For @RestController (which implies @ResponseBody), the handler picks an HttpMessageConverter by negotiating the request's Accept header against the types it can write, which means Jackson for application/json. A ResponseEntity return gives you control of the status and headers; a plain object defaults to 200.
curl -i -H 'Accept: application/json' localhost:8080/orders/7HTTP/1.1 200
Content-Type: application/json
Content-Length: 41
{"id":7,"status":"PAID","totalCents":4999}A controller that returned a String instead of using @ResponseBody would be treated as a view name and sent to a ViewResolver, which is how server-rendered pages work and how a REST endpoint ends up trying to find a template called "ok". In a pure API, stay with @RestController.
Exceptions are resolved, not thrown
An exception from any step above does not travel up to the servlet container as a stack trace. DispatcherServlet catches it and asks a chain of HandlerExceptionResolver beans to turn it into a response. The first one that handles it wins. @ExceptionHandler methods and @ControllerAdvice classes are the resolver you write:
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(OrderNotFound.class)
ProblemDetail notFound(OrderNotFound e) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
pd.setTitle("Order not found");
return pd;
}
}HTTP/1.1 404
Content-Type: application/problem+json
{"type":"about:blank","title":"Order not found","status":404,"detail":"No order 7","instance":"/orders/7"}Without a matching handler, Spring's default resolvers translate known exceptions to the right status (for example HttpRequestMethodNotSupportedException to 405), and unknown ones become a 500 through Boot's /error page. The filter's finally block above still runs and logs the final status in every case.
Where this model stops
Some request types do not follow this path exactly. A request for a static file is served by a resource handler and never reaches a controller. A WebSocket upgrade is handled by a different handler. With Spring WebFlux there is no DispatcherServlet, and a DispatcherHandler with functional or annotated routing takes its place, on a non-blocking runtime. Asynchronous return types such as Callable or DeferredResult release the servlet thread and complete the response later on another dispatch. And with virtual threads enabled, the flow above is the same, only each request runs on a virtual thread. The reference for the whole sequence is the DispatcherServlet chapter and the Spring Web MVC reference. To build a full API on this foundation, see building a Spring MVC REST API.


