Video in progress

Strong Middle 🌱 Spring

What path does an HTTP request take to a controller method in Spring MVC?

Tomcat → servlet filters (Security lives here too) → DispatcherServlet → HandlerMapping finds the controller method → interceptors → HandlerAdapter prepares the arguments (reads JSON, validates) → the method → an HttpMessageConverter writes the response.

📖 Answer

Step by step:

  1. Tomcat accepts the connection and hands the request to a worker thread.
  2. Filters: CharacterEncodingFilter, the Spring Security chain, your own OncePerRequestFilters.
  3. DispatcherServlet, the single entry point into Spring MVC.
  4. HandlerMapping (RequestMappingHandlerMapping) finds the method by URL, HTTP method and consumes/produces. If it can't, you get 404; if the method doesn't match, 405.
  5. HandlerInterceptor.preHandle, for example for language or audit.
  6. HandlerAdapter: the HandlerMethodArgumentResolvers fill in the parameters: @PathVariable, @RequestBody (Jackson), @AuthenticationPrincipal. @Valid is checked here too.
  7. The controller method is called.
  8. The HandlerMethodReturnValueHandler takes the returned value; with @ResponseBody, an HttpMessageConverter writes it as JSON.
  9. If an exception is thrown, a HandlerExceptionResolver handles it (@ExceptionHandler and @ControllerAdvice work here).
  10. postHandle/afterCompletion, then the filters in reverse order.

This is very handy when debugging. For example, @ControllerAdvice doesn't fire for a request rejected in a Security filter, because the request never reached the DispatcherServlet.