Skip to main content
Advertisement

4.2 DispatcherServlet and the Request Lifecycle

At the core of the Spring MVC architecture lies the DispatcherServlet, implementing the Front Controller pattern. Every HTTP request entering the application goes through the DispatcherServlet first.

1. Front Controller Pattern

It is an architectural pattern that receives all client requests through a single entry point (a Servlet), performs common processing (such as routing, parameter validation, encoding normalization), and then delegates the request to the appropriate controller logic.

2. How the DispatcherServlet Works

When a client calls a URL, the request is processed in the following order:

  1. Receive Client Request: A Servlet container like Tomcat receives the HTTP request and passes it to the DispatcherServlet.
  2. Consult HandlerMapping: The DispatcherServlet searches for a Controller (Handler) capable of handling the request (typically indexing methods annotated with @GetMapping).
  3. Find HandlerAdapter: It searches for an execution mechanism, a HandlerAdapter, capable of invoking that specific controller method.
  4. Execute Handler: The adapter executes the actual business code of the controller.
  5. Return ModelAndView: The controller packages the processing results into a ModelAndView and returns it. In the case of REST APIs, views are not rendered; instead, responses are converted directly into JSON via HttpMessageConverter.
  6. Process via ViewResolver: If it's a standard Server-Side Rendering (SSR) scenario, a ViewResolver uses the view name (e.g., "home") to locate the physical template path.
  7. HTTP Response: The rendered result is transmitted back to the browser.
// Pseudo-code of the core structure of Spring's DispatcherServlet
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) {
// 1. Find the Handler (Controller)
HandlerExecutionChain mappedHandler = getHandler(request);

// 2. Find the Adapter
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

// 3. Actually execute the Controller
ModelAndView mv = ha.handle(request, response, mappedHandler.getHandler());

// 4. Render the View
processDispatchResult(request, response, mappedHandler, mv, dispatchException);
}
Advertisement