Back to Web Layer: Controllers & Request Mapping
Q4Question 4 of 6

What is DispatcherServlet in Spring MVC

Answer: DispatcherServlet is the front controller in Spring MVC that receives every HTTP request, finds the matching controller method through HandlerMapping, invokes it through HandlerAdapter, and returns the response through a ViewResolver or HttpMessageConverter.

Key Concepts
  • DispatcherServlet is the single entry point (front controller) for all HTTP requests in a Spring MVC application, registered automatically by Spring Boot on the / URL pattern.
  • It delegates to HandlerMapping to find the right controller method, HandlerAdapter to invoke it, and ViewResolver (or HttpMessageConverter for REST) to produce the response.
  • Spring Boot auto-configures DispatcherServlet through DispatcherServletAutoConfiguration when spring-boot-starter-web is on the classpath.
  • HandlerInterceptors run before and after the controller method, providing cross-cutting concerns like logging, authentication, and timing.
  • DispatcherServlet catches exceptions from controllers and delegates them to HandlerExceptionResolver, which includes @ControllerAdvice and @ExceptionHandler.
  • In Spring Boot, DispatcherServlet runs inside an embedded Tomcat (or Jetty/Undertow) server, so there is no external servlet container to configure.

Definition

DispatcherServlet is the front controller in Spring MVC that receives every HTTP request, finds the matching controller method through HandlerMapping, invokes it through HandlerAdapter, and returns the response through a ViewResolver or HttpMessageConverter.
  • DispatcherServlet is a Servlet (extends HttpServlet) that acts as the single entry point for all HTTP requests in a Spring MVC application; it is the implementation of the Front Controller design pattern.
  • HandlerMapping is the component that maps an incoming request URL and HTTP method to a specific controller method; RequestMappingHandlerMapping handles @RequestMapping annotations.
  • HandlerAdapter is the component that invokes the resolved controller method, handling parameter binding, @RequestBody deserialization, and return value processing.
  • HandlerInterceptor is an interface with preHandle, postHandle, and afterCompletion methods that run around controller execution for cross-cutting concerns.
  • HandlerExceptionResolver processes exceptions thrown by controllers, delegating to @ExceptionHandler methods in @ControllerAdvice classes.

Think of National Bank of India's main branch front desk. Every customer (HTTP request) walks through a single entrance (DispatcherServlet). The receptionist (HandlerMapping) checks the customer's request slip and directs them to the right counter: savings counter, loan counter, or foreign exchange counter (controller methods). The counter staff (HandlerAdapter) processes the request. Security guards (HandlerInterceptors) check ID before and stamp receipts after the transaction. If something goes wrong, the complaint desk (HandlerExceptionResolver) handles the issue. No customer bypasses the front desk.

Understanding the Concepts

What is DispatcherServlet?

DispatcherServlet is a Java Servlet that Spring MVC uses as the front controller. Every HTTP request to your application goes through DispatcherServlet first. It does not handle the request itself. Instead, it delegates to specialized components: HandlerMapping finds the controller, HandlerAdapter calls it, and a converter or resolver produces the response.

In Spring Boot, DispatcherServlet is auto-configured and mapped to the root URL pattern (/). You do not configure it manually.

JAVA
package com.bank;

public class DispatcherServletExplained {
    public static void main(String[] args) {
        System.out.println("DispatcherServlet request flow:");
        System.out.println("  1. Client sends: GET /api/accounts/SAV2001");
        System.out.println("  2. Tomcat receives the request");
        System.out.println("  3. DispatcherServlet.doDispatch() is called");
        System.out.println("  4. HandlerMapping finds: AccountController.getAccount()");
        System.out.println("  5. HandlerInterceptor.preHandle() runs (e.g., logging)");
        System.out.println("  6. HandlerAdapter invokes AccountController.getAccount(\"SAV2001\")");
        System.out.println("  7. Controller returns Account object");
        System.out.println("  8. HandlerInterceptor.postHandle() runs");
        System.out.println("  9. HttpMessageConverter serializes Account to JSON");
        System.out.println("  10. Response: 200 OK with JSON body");
    }
}
TEXT
Expected output:
DispatcherServlet request flow:
  1. Client sends: GET /api/accounts/SAV2001
  2. Tomcat receives the request
  3. DispatcherServlet.doDispatch() is called
  4. HandlerMapping finds: AccountController.getAccount()
  5. HandlerInterceptor.preHandle() runs (e.g., logging)
  6. HandlerAdapter invokes AccountController.getAccount("SAV2001")
  7. Controller returns Account object
  8. HandlerInterceptor.postHandle() runs
  9. HttpMessageConverter serializes Account to JSON
  10. Response: 200 OK with JSON body

Why does DispatcherServlet exist (Front Controller pattern)?

Without a front controller, every URL needs a separate servlet mapped in web.xml. With 50 endpoints, you need 50 servlet mappings. The Front Controller pattern centralizes request handling into a single servlet.

DispatcherServlet provides a single place for cross-cutting concerns: logging, security, error handling, content negotiation. Every request passes through it, so you configure these once.

JAVA
package com.bank;

public class WhyDispatcherServlet {
    public static void main(String[] args) {
        System.out.println("Without Front Controller (old servlet approach):");
        System.out.println("  /accounts -> AccountServlet");
        System.out.println("  /payments -> PaymentServlet");
        System.out.println("  /loans    -> LoanServlet");
        System.out.println("  50 endpoints = 50 servlets + 50 web.xml entries");
        System.out.println("  Logging? Add to each servlet.");
        System.out.println("  Auth? Add to each servlet.");
        System.out.println();
        System.out.println("With Front Controller (DispatcherServlet):");
        System.out.println("  /* -> DispatcherServlet");
        System.out.println("  DispatcherServlet -> HandlerMapping -> correct controller");
        System.out.println("  Logging? One interceptor.");
        System.out.println("  Auth? One interceptor.");
        System.out.println("  50 endpoints = 50 @RequestMapping methods, 1 servlet");
    }
}
TEXT
Expected output:
Without Front Controller (old servlet approach):
  /accounts -> AccountServlet
  /payments -> PaymentServlet
  /loans    -> LoanServlet
  50 endpoints = 50 servlets + 50 web.xml entries
  Logging? Add to each servlet.
  Auth? Add to each servlet.

With Front Controller (DispatcherServlet):
  /* -> DispatcherServlet
  DispatcherServlet -> HandlerMapping -> correct controller
  Logging? One interceptor.
  Auth? One interceptor.
  50 endpoints = 50 @RequestMapping methods, 1 servlet

How does DispatcherServlet work internally?

The core method is doDispatch(). Here is what happens inside it, step by step:

  1. getHandler(): iterates through registered HandlerMapping beans to find a handler for the request. Returns a HandlerExecutionChain (handler + interceptors).
  2. getHandlerAdapter(): finds a HandlerAdapter that can invoke the handler. For @RequestMapping methods, it is RequestMappingHandlerAdapter.
  3. preHandle(): calls preHandle on each interceptor in the chain. If any returns false, the request is aborted.
  4. handle(): the adapter invokes the controller method. Parameters are bound from the request (path variables, query params, request body).
  5. postHandle(): calls postHandle on each interceptor in reverse order.
  6. processDispatchResult(): if the handler returned a view name, ViewResolver resolves it. If it returned an object with @ResponseBody, HttpMessageConverter serializes it.
  7. afterCompletion(): calls afterCompletion on each interceptor, even if an exception occurred.
JAVA
package com.bank;

public class DoDispatchInternals {
    public static void main(String[] args) {
        System.out.println("DispatcherServlet.doDispatch() internals:");
        System.out.println("  1. getHandler(request)");
        System.out.println("     -> RequestMappingHandlerMapping");
        System.out.println("     -> returns HandlerExecutionChain");
        System.out.println();
        System.out.println("  2. getHandlerAdapter(handler)");
        System.out.println("     -> RequestMappingHandlerAdapter");
        System.out.println();
        System.out.println("  3. interceptor.preHandle(request, response, handler)");
        System.out.println("     -> true: continue, false: abort");
        System.out.println();
        System.out.println("  4. adapter.handle(request, response, handler)");
        System.out.println("     -> invokes @GetMapping method");
        System.out.println("     -> binds @PathVariable, @RequestParam, @RequestBody");
        System.out.println();
        System.out.println("  5. interceptor.postHandle(request, response, handler, modelAndView)");
        System.out.println();
        System.out.println("  6. processDispatchResult()");
        System.out.println("     -> @ResponseBody: Jackson serializes to JSON");
        System.out.println("     -> view name: ViewResolver renders template");
        System.out.println();
        System.out.println("  7. interceptor.afterCompletion(request, response, handler, ex)");
    }
}
TEXT
Expected output:
DispatcherServlet.doDispatch() internals:
  1. getHandler(request)
     -> RequestMappingHandlerMapping
     -> returns HandlerExecutionChain

  2. getHandlerAdapter(handler)
     -> RequestMappingHandlerAdapter

  3. interceptor.preHandle(request, response, handler)
     -> true: continue, false: abort

  4. adapter.handle(request, response, handler)
     -> invokes @GetMapping method
     -> binds @PathVariable, @RequestParam, @RequestBody

  5. interceptor.postHandle(request, response, handler, modelAndView)

  6. processDispatchResult()
     -> @ResponseBody: Jackson serializes to JSON
     -> view name: ViewResolver renders template

  7. interceptor.afterCompletion(request, response, handler, ex)

What is a complete banking project showing DispatcherServlet in action?

This project traces a payment API request through DispatcherServlet with a custom HandlerInterceptor that logs timing at each step.

Project structure

DIAGRAM
bank-dispatcher-demo/
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── com/
    │           └── bank/
    │               ├── BankDispatcherDemoApp.java
    │               ├── model/
    │               │   └── Account.java
    │               ├── controller/
    │               │   └── AccountController.java
    │               ├── service/
    │               │   └── AccountService.java
    │               ├── interceptor/
    │               │   └── RequestTimingInterceptor.java
    │               └── config/
    │                   └── WebConfig.java
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── controller/
                        └── AccountControllerTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>bank-dispatcher-demosyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

Account.java

JAVA
package com.bank.model;

import java.math.BigDecimal;

public record Account(
    String accountId,
    String holderName,
    BigDecimal balance,
    String type
) {}

AccountService.java

JAVA
package com.bank.service;

import com.bank.model.Account;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;

@Service
public class AccountService {

    private final Map<String, Account> store = Map.of(
        "SAV2001", new Account("SAV2001", "Priya", new BigDecimal("150000.00"), "SAVINGS"),
        "CUR3001", new Account("CUR3001", "Rajesh", new BigDecimal("500000.00"), "CURRENT")
    );

    public Optional<Account> findById(String id) {
        return Optional.ofNullable(store.get(id));
    }
}

RequestTimingInterceptor.java

JAVA
package com.bank.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class RequestTimingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        System.out.println("[Interceptor] preHandle: "
            + request.getMethod() + " " + request.getRequestURI());
        return true; // Continue to controller
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) {
        System.out.println("[Interceptor] postHandle: controller returned");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        long startTime = (long) request.getAttribute("startTime");
        long duration = System.currentTimeMillis() - startTime;
        System.out.println("[Interceptor] afterCompletion: "
            + request.getRequestURI() + " took " + duration + "ms");
    }
}

WebConfig.java

JAVA
package com.bank.config;

import com.bank.interceptor.RequestTimingInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final RequestTimingInterceptor timingInterceptor;

    public WebConfig(RequestTimingInterceptor timingInterceptor) {
        this.timingInterceptor = timingInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timingInterceptor)
                .addPathPatterns("/api/**");
    }
}

AccountController.java

JAVA
package com.bank.controller;

import com.bank.model.Account;
import com.bank.service.AccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Account> getAccount(@PathVariable String id) {
        System.out.println("[Controller] getAccount called for: " + id);
        return accountService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
}

AccountControllerTest.java

JAVA
package com.bank.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void getAccount_returnsAccount() throws Exception {
        mockMvc.perform(get("/api/accounts/SAV2001"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.accountId").value("SAV2001"))
            .andExpect(jsonPath("$.holderName").value("Priya"));
        System.out.println("Test passed: GET /api/accounts/SAV2001");
    }

    @Test
    void getAccount_returnsNotFound() throws Exception {
        mockMvc.perform(get("/api/accounts/SAV9999"))
            .andExpect(status().isNotFound());
        System.out.println("Test passed: 404 for unknown account");
    }
}

BankDispatcherDemoApp.java

JAVA
package com.bank;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BankDispatcherDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(BankDispatcherDemoApp.class, args);
    }
}
TEXT
Expected output (curl http://localhost:8080/api/accounts/SAV2001):

Server console:
[Interceptor] preHandle: GET /api/accounts/SAV2001
[Controller] getAccount called for: SAV2001
[Interceptor] postHandle: controller returned
[Interceptor] afterCompletion: /api/accounts/SAV2001 took 3ms

HTTP response:
{"accountId":"SAV2001","holderName":"Priya","balance":150000.00,"type":"SAVINGS"}

How to run

BASH
cd bank-dispatcher-demo
mvn clean package -DskipTests
java -jar target/bank-dispatcher-demo-1.0.0.jar

curl http://localhost:8080/api/accounts/SAV2001
curl http://localhost:8080/api/accounts/SAV9999

mvn test

How is DispatcherServlet different from a Servlet Filter?

FeatureServlet FilterDispatcherServlet + Interceptor
ScopeAll servlets (Servlet API level)Only Spring MVC requests
APIjavax.servlet.FilterHandlerInterceptor
Access to handlerNo (does not know which controller)Yes (handler parameter)
Exception handlingManualIntegrated with @ControllerAdvice
Spring beansNot injected by defaultFull Spring injection
OrderConfigured in FilterRegistrationBeanConfigured in InterceptorRegistry
Use caseCORS, encoding, securityLogging, timing, auth checks
JAVA
package com.bank;

public class FilterVsInterceptor {
    public static void main(String[] args) {
        System.out.println("Request processing order:");
        System.out.println("  1. Servlet Filter (runs before DispatcherServlet)");
        System.out.println("  2. DispatcherServlet receives request");
        System.out.println("  3. HandlerInterceptor.preHandle()");
        System.out.println("  4. Controller method");
        System.out.println("  5. HandlerInterceptor.postHandle()");
        System.out.println("  6. Response rendered (JSON or view)");
        System.out.println("  7. HandlerInterceptor.afterCompletion()");
        System.out.println("  8. Servlet Filter (runs after DispatcherServlet)");
    }
}
TEXT
Expected output:
Request processing order:
  1. Servlet Filter (runs before DispatcherServlet)
  2. DispatcherServlet receives request
  3. HandlerInterceptor.preHandle()
  4. Controller method
  5. HandlerInterceptor.postHandle()
  6. Response rendered (JSON or view)
  7. HandlerInterceptor.afterCompletion()
  8. Servlet Filter (runs after DispatcherServlet)

What are common mistakes with DispatcherServlet?

Wrong: returning void from a @RestController method without writing the response

JAVA
package com.bank.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WrongController {

    @GetMapping("/api/ping")
    public void ping() {
        // WRONG: returns void, response body is empty
        System.out.println("Ping received");
    }
}
TEXT
Problem: the response has status 200 but an empty body.
The caller receives no content. DispatcherServlet has nothing to serialize.
Use ResponseEntity or return a value.

Correct: return a value or ResponseEntity

JAVA
package com.bank.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class CorrectController {

    @GetMapping("/api/ping")
    public Map<String, String> ping() {
        return Map.of("status", "ok", "service", "National Bank of India");
    }
}
TEXT
Correct: returns a Map, Jackson serializes it to JSON.
Response: {"status":"ok","service":"National Bank of India"}

What should a senior or principal engineer know?

  • DispatcherServlet initialization: in Spring Boot, DispatcherServletAutoConfiguration creates the DispatcherServlet bean and registers it with the embedded server. The servlet is mapped to / by default. You can change it with server.servlet.context-path.
  • Multiple DispatcherServlets: you can register multiple DispatcherServlet instances with different URL mappings. Each has its own WebApplicationContext. This is rare but useful for separating public and admin APIs.
  • Async request handling: DispatcherServlet supports async processing via Callable and DeferredResult. The servlet thread is released during async computation, and the response is written when the result is available.
  • doDispatch() error handling: if a controller throws an exception, doDispatch catches it and delegates to HandlerExceptionResolver. If no resolver handles it, the exception propagates to the servlet container's error page.
  • FlashMap: DispatcherServlet manages FlashMap for redirect attributes. Flash attributes survive one redirect and are then removed.
JAVA
package com.bank.core;

public class SeniorDispatcherKnowledge {
    public static void main(String[] args) {
        System.out.println("Senior/Principal DispatcherServlet Checklist:");
        System.out.println("  1. Auto-configured by DispatcherServletAutoConfiguration");
        System.out.println("  2. Mapped to / by default, change with server.servlet.context-path");
        System.out.println("  3. doDispatch() is the core method: find handler, call it, resolve view");
        System.out.println("  4. Multiple DispatcherServlets possible for separate API groups");
        System.out.println("  5. Async: Callable and DeferredResult release the servlet thread");
        System.out.println("  6. Exceptions -> HandlerExceptionResolver -> @ControllerAdvice");
        System.out.println("  7. FlashMap for redirect attributes (survive one redirect)");
    }
}
TEXT
Expected output:
Senior/Principal DispatcherServlet Checklist:
  1. Auto-configured by DispatcherServletAutoConfiguration
  2. Mapped to / by default, change with server.servlet.context-path
  3. doDispatch() is the core method: find handler, call it, resolve view
  4. Multiple DispatcherServlets possible for separate API groups
  5. Async: Callable and DeferredResult release the servlet thread
  6. Exceptions -> HandlerExceptionResolver -> @ControllerAdvice
  7. FlashMap for redirect attributes (survive one redirect)

What are common interview follow-up questions?

  • Can you have a Spring Boot application without DispatcherServlet? (Yes. If you use spring-boot-starter without spring-boot-starter-web, there is no DispatcherServlet. Also, Spring WebFlux uses a different reactive handler.)
  • What is the difference between DispatcherServlet and DispatcherHandler in WebFlux? (DispatcherServlet is blocking, servlet-based. DispatcherHandler is non-blocking, reactive, uses Project Reactor.)
  • How does DispatcherServlet know which controller to call? (HandlerMapping. RequestMappingHandlerMapping maps @RequestMapping annotations to methods. It builds a registry at startup.)
  • What happens if two @RequestMapping methods match the same URL? (Spring throws IllegalStateException at startup: Ambiguous handler methods mapped.)
  • Can interceptors modify the response? (postHandle runs before the response is committed, so you can add headers. afterCompletion runs after the response is committed, so you can only log.)
  • How do you register a Servlet Filter in Spring Boot? (Create a FilterRegistrationBean @Bean. Or annotate the filter with @Component and it is auto-registered on all URL patterns.)

Visual Overview

DIAGRAM
 DispatcherServlet Request Processing
 ======================================

 Client
   │
   │  GET /api/accounts/SAV2001
   ▼
 ┌──────────────────────────────┐
 │ Embedded Tomcat               │
 │ (receives HTTP request)       │
 └──────────────┬───────────────┘
                │
                ▼
 ┌──────────────────────────────┐
 │ Servlet Filter Chain          │
 │ (CORS, encoding, security)    │
 └──────────────┬───────────────┘
                │
                ▼
 ┌──────────────────────────────┐
 │ DispatcherServlet              │
 │ doDispatch()                   │
 │                                │
 │ 1. HandlerMapping              │
 │    -> AccountController.get()  │
 │                                │
 │ 2. Interceptor.preHandle()     │
 │    -> log, auth, timing        │
 │                                │
 │ 3. HandlerAdapter.handle()     │
 │    -> invoke controller method │
 │    -> bind @PathVariable       │
 │                                │
 │ 4. Interceptor.postHandle()    │
 │                                │
 │ 5. HttpMessageConverter        │
 │    -> Account -> JSON          │
 │                                │
 │ 6. Interceptor.afterCompletion │
 │    -> log timing               │
 └──────────────┬───────────────┘
                │
                ▼
 Client receives:
 {"accountId":"SAV2001","holderName":"Priya",...}

Key Takeaway

DispatcherServlet is the front controller of Spring MVC. Every HTTP request to your application enters through this single servlet, which delegates to specialized components to find the right controller, invoke it, and produce the response.

The processing sequence is predictable: HandlerMapping finds the controller method, HandlerInterceptor.preHandle runs first, HandlerAdapter invokes the controller, HandlerInterceptor.postHandle runs after, the response is rendered (JSON for REST, template for MVC), and HandlerInterceptor.afterCompletion runs last.

In our National Bank of India demo, we traced a GET /api/accounts/SAV2001 request through the entire pipeline. The RequestTimingInterceptor logged the start time in preHandle, the controller fetched the account, and afterCompletion calculated the total processing time. This is a common pattern for performance monitoring.

The key distinction between Servlet Filters and HandlerInterceptors is scope. Filters operate at the Servlet API level and run before DispatcherServlet. Interceptors operate at the Spring MVC level and have access to the handler (controller method) object. Use Filters for CORS and encoding. Use Interceptors for logging, timing, and authentication checks.

At the senior level, understand that doDispatch() is the core method, that Spring Boot auto-configures DispatcherServlet through DispatcherServletAutoConfiguration, and that async processing with Callable and DeferredResult releases the servlet thread during long-running operations.

Remember one sentence: DispatcherServlet is the single entry point that receives every HTTP request, finds the matching controller through HandlerMapping, invokes it through HandlerAdapter, and returns the response through an HttpMessageConverter or ViewResolver.

---

Share
Use ← → arrow keys to navigate