DispatcherServlet

Basic Spring
≈ 2 min read

A single entry point into Spring MVC

In Spring MVC, most HTTP requests first reach the DispatcherServlet. It is a front controller: it does not contain the business logic of specific endpoints, but coordinates the other parts of the web layer. Its job is to determine who should handle the request, invoke that handler, and organize response creation.

A simplified request path looks like this:

  1. DispatcherServlet receives the HTTP request.
  2. Spring MVC finds a suitable controller method.
  3. The framework prepares the method arguments and invokes it.
  4. The returned value is converted into the required HTTP response representation.

Why a controller does not need the Servlet API

Without such a layer, a handler would usually be more tightly coupled to objects such as HttpServletRequest and HttpServletResponse. DispatcherServlet together with the Spring MVC infrastructure hides much of that mechanics, so a controller method can work with more convenient Java types.

@GetMapping("/users/{id}")
UserDto user(@PathVariable long id) {
    return userService.find(id);
}

The method does not manually look for a parameter in the Servlet request or write JSON into the response itself. Spring MVC performs the glue work around it.

DispatcherServlet does not choose a controller method “by method name”. The choice is determined by the application's web mappings. We will cover those mappings separately.