Spring Framework
Dispatcher Servlet
Java
Web Development
MVC Pattern

What is Dispatcher Servlet in Spring?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

DispatcherServlet is the central request dispatcher in Spring MVC. It acts as a front controller that receives HTTP requests, routes them to handlers, and coordinates response rendering. Understanding this lifecycle makes debugging controller, validation, and exception issues much easier.

Front Controller Role

In Spring MVC, requests do not go directly to controller methods. They first pass through DispatcherServlet, which orchestrates processing steps.

Key responsibilities:

  • Find the right handler for a request.
  • Apply interceptors before and after handler execution.
  • Perform binding and conversion for method arguments.
  • Resolve exceptions into HTTP responses.
  • Render views or serialize response bodies.

This centralization enables consistent behavior across the web layer.

Request Lifecycle in Practice

A simplified request flow:

  1. Request arrives at DispatcherServlet.
  2. HandlerMapping identifies matching handler.
  3. HandlerAdapter invokes handler method.
  4. Return value is processed by view resolvers or message converters.
  5. Final HTTP response is written.

Even REST controllers go through this flow, though they usually skip template rendering.

Spring Boot Default Behavior

In Spring Boot, you usually do not configure DispatcherServlet manually. Boot auto-configures it with sensible defaults.

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RestController;
3
4@RestController
5class HealthController {
6    @GetMapping("/health")
7    String health() {
8        return "ok";
9    }
10}

Behind the scenes, DispatcherServlet maps /health, calls method, and writes response body through message conversion.

Manual Registration in Classic Setup

In non-Boot applications, you can register DispatcherServlet explicitly.

java
1import jakarta.servlet.ServletContext;
2import jakarta.servlet.ServletException;
3import jakarta.servlet.ServletRegistration;
4import org.springframework.web.WebApplicationInitializer;
5import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
6import org.springframework.web.servlet.DispatcherServlet;
7
8public class AppInitializer implements WebApplicationInitializer {
9    @Override
10    public void onStartup(ServletContext servletContext) throws ServletException {
11        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
12        context.register(WebConfig.class);
13
14        ServletRegistration.Dynamic dispatcher =
15                servletContext.addServlet("dispatcher", new DispatcherServlet(context));
16        dispatcher.setLoadOnStartup(1);
17        dispatcher.addMapping("/");
18    }
19}

This mode is useful when integrating with existing servlet container conventions.

Core Collaborators to Know

DispatcherServlet relies on strategy interfaces. Knowing them helps isolate failures quickly.

Main collaborators:

  • HandlerMapping for route lookup.
  • HandlerAdapter for invoking handlers.
  • HandlerExceptionResolver for exception translation.
  • ViewResolver for template view resolution.
  • HttpMessageConverter for JSON or XML body serialization.

Most runtime surprises come from one of these collaborators rather than controller logic itself.

MVC View Rendering Versus REST Serialization

A controller returning view name goes through ViewResolver:

java
1@GetMapping("/home")
2String home(Model model) {
3    model.addAttribute("name", "Ava");
4    return "home";
5}

A controller returning object in @RestController goes through message converters:

java
1@GetMapping("/api/user")
2UserDto user() {
3    return new UserDto("Ava");
4}

Same dispatcher, different response pipeline.

Interceptors and Cross-Cutting Logic

Interceptors integrate naturally because all matched requests pass through dispatcher-managed chain.

java
1import jakarta.servlet.http.HttpServletRequest;
2import jakarta.servlet.http.HttpServletResponse;
3import org.springframework.web.servlet.HandlerInterceptor;
4
5public class TimingInterceptor implements HandlerInterceptor {
6    @Override
7    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
8        request.setAttribute("startNs", System.nanoTime());
9        return true;
10    }
11}

This is cleaner than duplicating logging or auth checks in every controller.

Debugging Through Dispatcher Lifecycle

When request handling fails:

  • Verify route mapping first.
  • Check argument binding and validation errors.
  • Inspect converter support for return type.
  • Review exception resolver output.
  • Check interceptor order and side effects.

Tracing by pipeline stage is faster than guessing from controller code alone.

Common Pitfalls

  • Treating DispatcherServlet as optional in MVC architecture.
  • Overriding default beans without understanding their interaction order.
  • Confusing view rendering and REST serialization behavior.
  • Ignoring handler mapping conflicts with overlapping path patterns.
  • Debugging only controller code when issue is in resolver or converter layer.

Summary

  • DispatcherServlet is the front controller of Spring MVC.
  • It coordinates routing, invocation, exception handling, and response creation.
  • Spring Boot auto-configures it, while classic setups can register it manually.
  • Most web-layer behavior depends on its collaborator strategy interfaces.
  • Understanding its lifecycle is key to fast and accurate debugging.

Course illustration
Course illustration

All Rights Reserved.