Middle
How does the Dispatcher Servlet determine which method to invoke?
sobes.tech AI
Answer from AI
DispatcherServlet uses request mapping mechanisms to determine the handler (Controller) and the method within it that should process the incoming HTTP request.
Key steps:
- Receiving the request: DispatcherServlet intercepts all incoming HTTP requests.
- Finding HandlerMapping: DispatcherServlet consults registered HandlerMapping objects (e.g.,
RequestMappingHandlerMapping). - Matching URI and HTTP method: HandlerMapping analyzes the request URI and HTTP method (GET, POST, etc.) and compares them with
@RequestMappingannotations (or@GetMapping,@PostMapping, etc.) in controllers. - Determining HandlerExecutionChain: When a suitable controller and method are found, HandlerMapping returns a HandlerExecutionChain, which includes the handler itself and a list of Interceptors to be executed before and/or after the handler.
- Passing HandlerExecutionChain: DispatcherServlet passes the HandlerExecutionChain to the appropriate HandlerAdapter (e.g.,
RequestMappingHandlerAdapter). - Executing the handler: HandlerAdapter invokes the found controller method.
Examples of annotations used for mapping:
@RequestMapping: Main annotation for request mapping.// Java @Controller @RequestMapping("/users") public class UserController { @RequestMapping(method = RequestMethod.GET) // Matches GET /users public String getAllUsers() { return "users"; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) // Matches GET /users/{id} public String getUserById(@PathVariable Long id) { return "user"; } }@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,@PatchMapping: Shorthand annotations for mapping to specific HTTP methods.// Java @Controller @RequestMapping("/products") public class ProductController { @GetMapping // Matches GET /products public String getAllProducts() { return "products"; } @PostMapping // Matches POST /products public String createProduct() { return "product_created"; } }
DispatcherServlet uses reflection to invoke the specific method with the appropriate arguments, transforming request parameters (e.g., from URL, request body, headers) into the method's argument types.