How does a request flow through Spring MVC's DispatcherServlet?
Quick Answer
Every incoming HTTP request first hits the DispatcherServlet, Spring MVC's central front controller. It consults HandlerMapping to find which controller method should handle the request, passes it through any configured HandlerInterceptors, invokes the handler method (resolving its arguments via HandlerMethodArgumentResolvers), takes the returned value and — for @RestController methods — hands it to an HttpMessageConverter to write directly to the response, or for @Controller methods, resolves it to a View to render, with a HandlerExceptionResolver stepping in if anything throws along the way.
Detailed Answer
The DispatcherServlet is Spring MVC's single front controller — every HTTP request for the application passes through it first, and it orchestrates all the subsequent steps:
-
HandlerMapping— theDispatcherServletasks the configuredHandlerMapping(s) which handler (typically an@RequestMapping-annotated controller method) matches this request's URL, HTTP method, headers, etc. -
HandlerInterceptors — before invoking the handler, any registered interceptors'preHandle()methods run (can short-circuit the request, e.g., for auth checks). -
Argument resolution — the framework resolves each handler method parameter (
@PathVariable,@RequestParam,@RequestBody, ...) via the appropriateHandlerMethodArgumentResolver, converting raw request data into typed Java objects. -
Handler invocation — the actual controller method executes with its resolved arguments.
-
Return value handling:
- For an
@RestController(or a method with@ResponseBody), the return value is passed to an appropriateHttpMessageConverter(Jackson'sMappingJackson2HttpMessageConverterfor JSON, by default), which serializes it directly to the HTTP response body. - For a plain
@Controllerreturning a view name, theDispatcherServletconsults aViewResolverto locate the actualView(a Thymeleaf template, JSP, etc.) and renders it, typically with aModelpopulated by the controller.
- For an
-
Interceptors'
postHandle()/afterCompletion()run as the response is finalized. -
Exception handling — if any step throws, a
HandlerExceptionResolver(which is what powers@ExceptionHandler/@ControllerAdvice) gets a chance to convert the exception into an appropriate error response instead of an unhandled failure.
Request → DispatcherServlet → HandlerMapping (find handler)
→ HandlerInterceptor.preHandle()
→ Controller method invocation (args resolved)
→ HttpMessageConverter (JSON) or ViewResolver (view rendering)
→ HandlerInterceptor.postHandle() / afterCompletion()
→ Response
Understanding this pipeline is what makes it clear why a HandlerInterceptor runs differently from a servlet Filter (interceptors operate inside Spring MVC's dispatch, with access to the resolved handler; filters operate at the raw servlet level, before Spring MVC is even involved) — a common, related interview follow-up.