Junior — Middle
How does DispatcherServlet identify the specific controller class to handle an incoming request?
sobes.tech AI
Answer from AI
In Spring MVC, the DispatcherServlet class is responsible for routing HTTP requests to the appropriate controllers.
The identification of a specific controller occurs through a mechanism that matches URL requests with controller methods, implemented using:
-
HandlerMapping:
- The DispatcherServlet uses one or more HandlerMapping beans to find the suitable handler.
- Usually, this is RequestMappingHandlerMapping, which maps URLs and HTTP methods to methods annotated with
@RequestMappingor similar.
-
Annotations in controllers:
- Controller methods are marked with annotations indicating the path and HTTP method.
- For example,
@GetMapping("/users").
-
Searching and selecting the controller:
- The DispatcherServlet passes the request to HandlerMapping, which returns a HandlerMethod (controller method).
- Then, the DispatcherServlet invokes this method to handle the request.
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable String id) {
// request processing
}
}
When a GET /users/123 request is made, the DispatcherServlet finds the getUser method of the UserController class via HandlerMapping and calls it.