Step 1: User initiates a request
- All requests firstquilt
DispatcherServlet
(Front-end controller) intercept, it is the entrance to the entire process. -
DispatcherServlet
Inherited fromHttpServlet
,passor
WebApplicationInitializer
Configure the mapping path (such as/
)。
Step 2: Request Mapping
-
HandlerMapping
Find the corresponding URL, parameters, header and other information according to the requested URL, parameters, header and other information.Processor (Handler)。-
processorCould be
@Controller
The method in the annotated class, or implementationController
Interface class. -
Key interfaces:
RequestMappingHandlerMapping
(deal with@RequestMapping
Annotation).
-
processorCould be
- Matching rules:
@Controller public class UserController { @GetMapping("/users/{id}") public String getUser(@PathVariable Long id, Model model) { // Business logic } }
Step 3: Handler Adapter
-
HandlerAdapter
Responsible for calling processor methods, and handling parameter binding and return value conversion. -
Key implementation classes:
RequestMappingHandlerAdapter
(support@RequestMapping
method). -
Adaptation process:
- Analyze method parameters (such as
@RequestParam
、@RequestBody
)。 - Execute method logic.
- Process the return value (such as
ModelAndView
, JSON data).
- Analyze method parameters (such as
Step 4: Execute Interceptor
-
HandlerInterceptor
Insert 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
-
ViewResolver
Resolve the view name returned by the controller into a specificView
Object. -
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
-
View
The 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: By
HttpMessageConverter
Serialize the return value to JSON (such as@ResponseBody
)。
Step 8: Return to the response
The rendered response passesDispatcherServlet
Return 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@Controller
and@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 request
Accept
Header 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:passHandlerMethodArgumentResolver
Analyze method parameters.
3. Return value processing:passHandlerMethodReturnValueHandler
Process 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!