SoFunction
Updated on 2025-04-15

Detailed explanation of Spring MVC request processing process steps

Step 1: User initiates a request

  • All requests firstquiltDispatcherServletFront-end controller) intercept, it is the entrance to the entire process.
  • DispatcherServletInherited fromHttpServlet,passorWebApplicationInitializerConfigure the mapping path (such as/)。

Step 2: Request Mapping

  • HandlerMappingFind the corresponding URL, parameters, header and other information according to the requested URL, parameters, header and other information.Processor (Handler)
    • processorCould be@ControllerThe method in the annotated class, or implementationControllerInterface class.
    • Key interfacesRequestMappingHandlerMapping(deal with@RequestMappingAnnotation).
  • Matching rules
@Controller
public class UserController {
    @GetMapping("/users/{id}")
    public String getUser(@PathVariable Long id, Model model) {
        // Business logic    }
}

Step 3: Handler Adapter

  • HandlerAdapterResponsible for calling processor methods, and handling parameter binding and return value conversion.
  • Key implementation classesRequestMappingHandlerAdapter(support@RequestMappingmethod).
  • Adaptation process
    • Analyze method parameters (such as@RequestParam@RequestBody)。
    • Execute method logic.
    • Process the return value (such asModelAndView, JSON data).

Step 4: Execute Interceptor

  • HandlerInterceptorInsert logic before and after processor execution:
    • preHandle: Called before the processor method is executed (such as permission verification).
    • postHandle: Called after the processor method is executed and before the view rendering.
    • afterCompletion: Called after the request is completed (resource cleanup).

Step 5: Business logic processing

  • The controller method executes business logic, which may involve:
    • Call the Service layer to process data.
    • Operation Model objects pass data to the view.
@GetMapping("/users")
public String listUsers(Model model) {
    List<User> users = ();
    ("users", users); // Data is passed to the view    return "user/list"; // View name}

Step 6: View Resolver

  • ViewResolverResolve the view name returned by the controller into a specific ViewObject.
  • Common implementations
    • InternalResourceViewResolver: parsing JSP pages (such as/WEB-INF/views/user/)。
    • ThymeleafViewResolver: parsing the Thymeleaf template.
  • Configuration example
@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    ("/WEB-INF/views/");
    (".jsp");
    return resolver;
}

Step 7: View Rendering

  • ViewThe object renders the model data into the response (such as generating HTML, JSON).
  • Rendering method
    • JSP: Use JSTL or EL expressions to fill data.
    • REST API: ByHttpMessageConverterSerialize the return value to JSON (such as@ResponseBody)。

Step 8: Return to the response

The rendered response passesDispatcherServletReturn to the client.

Key components and interfaces

Components Responsibilities
DispatcherServlet Front-end controller, unified scheduling request processing process.
HandlerMapping Map requests to the processor (Controller method).
HandlerAdapter Call the processor method to handle parameter binding and return value.
ViewResolver Resolve view names to specific view implementations (such as JSP, Thymeleaf).
HandlerInterceptor Intercept requests and implement preprocessing and post-processing logic (such as logs, permission verification).
HttpMessageConverter Processing data transformations of request/response (such as JSON ↔ Java objects).

Exception handling mechanism

@ExceptionHandler: Handle specific exceptions within the Controller.

@ExceptionHandler()
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
    return (HttpStatus.NOT_FOUND).body(());
}
  • HandlerExceptionResolver: Global exception parser, custom exception response.
  • @ControllerAdvice: Define global exception handling class.
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler()
    public ModelAndView handleAllExceptions(Exception ex) {
        ModelAndView mav = new ModelAndView("error");
        ("message", ());
        return mav;
    }
}

RESTful request processing

@RestController: Combination@Controllerand@ResponseBody, directly return the data.

@RestController
@RequestMapping("/api/users")
public class UserApiController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return (id);
    }
}
  • Content negotiation: According to the requestAcceptHeader returns JSON/XML and other formats (throughHttpMessageConverter)。

Source code-level process analysis (simplified version)

()

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HandlerExecutionChain mappedHandler = getHandler(request); // Get the processor chain    HandlerAdapter ha = getHandlerAdapter(());
    ModelAndView mv = (request, response, ());
    processDispatchResult(request, response, mappedHandler, mv, dispatchException);
}

2. Parameter analysis:passHandlerMethodArgumentResolverAnalyze method parameters.

3. Return value processing:passHandlerMethodReturnValueHandlerProcess the return value.

Summarize

  • Core process:DispatcherServlet → HandlerMapping → HandlerAdapter → Interceptor → ViewResolver。
  • Expansion Point: Interceptor, exception handler, custom parameter parser.
  • Design Thoughts: Separate responsibilities, componentization, highly customizable.

This is the end of this article about the detailed explanation of the Spring MVC request processing process. For more related Spring MVC request processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!