Sobes.tech
Middle+

How does DispatcherServlet determine which controller method to invoke?

sobes.tech AI

Answer from AI

DispatcherServlet uses request handlers (Handler Mappings) to determine the controller and method that correspond to an incoming HTTP request.

Main steps:

  1. Receiving the request: DispatcherServlet receives the HTTP request.
  2. Searching for HandlerMapping: DispatcherServlet iterates through configured HandlerMappings (e.g., RequestMappingHandlerMapping).
  3. Matching the request: Each HandlerMapping attempts to match the request with a controller and method, using information from the request (URL, HTTP method, headers, etc.) and controller metadata (e.g., @RequestMapping annotation).
  4. Determining the handler: Upon successful matching, HandlerMapping returns a HandlerExecutionChain object, which contains information about the handler (usually a controller method) and a list of interceptors.
  5. Executing interceptors: DispatcherServlet performs pre-processing using interceptors (HandlerInterceptor.preHandle()).
  6. Calling the controller method: If interceptors permit, DispatcherServlet invokes the corresponding controller method via HandlerAdapter (e.g., RequestMappingHandlerAdapter). HandlerAdapter is responsible for converting request arguments into controller method parameters and converting the method's return value into an HTTP response (e.g., ModelAndView, String, JSON, etc.).
  7. Post-processing and rendering: After executing the controller method, DispatcherServlet performs post-processing with interceptors (HandlerInterceptor.postHandle()), determines the View (if necessary) via ViewResolver, and renders the response, executing HandlerInterceptor.afterCompletion() after the response is sent.

Typical HandlerMappings in Spring MVC:

  • RequestMappingHandlerMapping: Based on annotations like @RequestMapping, @GetMapping, @PostMapping, etc. The most commonly used.
  • SimpleUrlHandlerMapping: Maps URL paths directly to controller or factory bean names.
  • BeanNameUrlHandlerMapping: Maps URL paths to bean names of controllers.

Example of using @RequestMapping:

// Example controller
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/users") // Class-level annotation
public class UserController {

    @GetMapping("/hello") // Method-level annotation
    @ResponseBody // Indicates that the return value should be the response body
    public String sayHello() {
        return "Hello from user controller!";
    }
}

In this example, when a GET request is made to /api/users/hello, RequestMappingHandlerMapping will find the UserController and invoke the sayHello() method.

How does DispatcherServlet determine which controller… - sobes.tech