skip to content

DispatcherServlet Front Controller

DispatcherServlet is the single front controller: it bootstraps the strategy beans and, on every request, runs doDispatch to find a handler, invoke it and render the result. Being able to narrate that flow is the standard Spring MVC interview set-piece.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What is the DispatcherServlet in Spring MVC, and what design pattern does it implement?

level: juniorimportance: must knowfreq 80%

answer

  1. Single entry point = Front Controller
  2. It's a real Servlet (extends FrameworkServlet)
  3. Delegates to HandlerMapping/Adapter
  4. Boot maps it to '/'
  5. Stateless, one instance for all requests

basics

~10 s

DispatcherServlet is Spring MVC's single entry point for HTTP requests. It implements the Front Controller pattern: one servlet receives every request and delegates to the right handler (controller), then renders the response.

solid answer

~40 s

DispatcherServlet is a Java Servlet that acts as Spring MVC's Front Controller — a single central entry point that all matching HTTP requests pass through. Instead of many servlets, one DispatcherServlet receives the request, then delegates: it asks a HandlerMapping which controller handles the URL, invokes it via a HandlerAdapter, and turns the result into a response (via a view or message converter). This centralizes cross-cutting concerns like locale, theme, multipart parsing, and exception handling in one place. In Spring Boot it's auto-registered and mapped to '/' by default. The pattern's value is a single, consistent request-processing pipeline that all requests share, keeping controllers free of infrastructure code.

code

java · 15 lines
java
// You rarely write this — Spring Boot does it. Manual (non-Boot) registration:
public class MyWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext ctx =
            new AnnotationConfigWebApplicationContext();
        ctx.register(WebConfig.class);

        DispatcherServlet dispatcher = new DispatcherServlet(ctx);
        ServletRegistration.Dynamic reg =
            container.addServlet("dispatcher", dispatcher);
        reg.setLoadOnStartup(1);
        reg.addMapping("/"); // front controller for all requests
    }
}

go deeper

for a junior

Know it's the single entry point (front controller) that delegates to controllers.

for a middle

Name the special beans it delegates to and that Boot maps it to '/'.

for a senior

Explain the delegation pipeline and that it's a stateless singleton servlet in the filter chain.

for a principal

Discuss why centralizing the pipeline matters architecturally and how it composes with the servlet/filter stack and security.

## What it is The **DispatcherServlet** is the heart of Spring MVC (the `spring-webmvc` module). It is a real Java **Servlet** (extends `org.springframework.web.servlet.FrameworkServlet` → `HttpServletBean` → `javax/jakarta.servlet.http.HttpServlet`). It implements the **Front Controller** design pattern. ### Front Controller pattern In plain Servlet apps you might register many servlets, each mapped to a URL, each duplicating boilerplate (parsing, auth checks, view rendering). The Front Controller pattern says: route **every** request through a **single** controller servlet that owns the shared request-processing pipeline and then **delegates** the actual work to per-request handlers. Benefits: one place for cross-cutting behavior (locale resolution, multipart handling, exception mapping, view rendering), and thin controllers that only contain business logic. ### How requests reach it The servlet container (Tomcat/Jetty/Undertow) maps incoming HTTP requests to the DispatcherServlet based on its URL mapping. In Spring Boot the default mapping is `'/'` (everything except other explicitly mapped servlets and static resources handled specially). You can change it with the property `spring.mvc.servlet.path`. ### What it delegates to (the 'special beans') Once a request arrives, DispatcherServlet doesn't do the routing logic itself — it consults a set of collaborating strategy beans it discovers at startup: - **HandlerMapping** — maps a request to a handler (e.g. an `@RequestMapping` method). - **HandlerAdapter** — knows how to actually invoke that handler. - **HandlerExceptionResolver** — turns thrown exceptions into responses. - **ViewResolver / View**, **LocaleResolver**, **ThemeResolver**, **MultipartResolver**, **FlashMapManager**, **RequestToViewNameTranslator**. (These individual strategies are covered in sibling topics — here the point is that DispatcherServlet *orchestrates* them.) ### When you interact with it Most developers never write `DispatcherServlet` code directly — Spring Boot auto-configures and registers it. You touch it when: customizing its URL mapping, registering more than one DispatcherServlet, tuning `throwExceptionIfNoHandlerFound`, or debugging why a request 404s at the framework level. ### Gotchas - It is **not** thread-per-instance: a **single** DispatcherServlet instance serves all requests concurrently; it must be stateless (it is). - 'It's just a servlet' — so it participates in the normal servlet filter chain; Spring Security filters run **before** it. - Static resource requests may be handled by a default servlet, not your controllers, even though the mapping is `'/'`.

  • Does DispatcherServlet handle the routing logic itself?
    No — it orchestrates. It delegates to HandlerMapping to find the handler and HandlerAdapter to invoke it; DispatcherServlet only runs the pipeline.
  • How many DispatcherServlet instances exist by default?
    One, mapped to '/'. You can register multiple, each with its own mapping and its own child WebApplicationContext.

saying these in an interview costs you the question

  • Saying each controller is its own servlet
  • Thinking DispatcherServlet does URL-to-method matching itself instead of delegating to HandlerMapping
  • Claiming it holds per-request state

context

open as a page

Walk through the doDispatch() flow: what happens inside DispatcherServlet when a request arrives?

level: middleimportance: must knowfreq 72%

basics

~10 s

doDispatch finds a handler via HandlerMapping, gets a HandlerAdapter, runs interceptor preHandle, invokes the handler to get a ModelAndView, runs postHandle, then renders the view (or writes the body) and runs afterCompletion.

open as a page

Explain the WebApplicationContext hierarchy in a DispatcherServlet setup: root context vs. servlet context.

level: seniorimportance: should knowfreq 48%

basics

~20 s

Classic Spring MVC has two contexts: a root WebApplicationContext (services, repositories, shared beans) loaded by ContextLoaderListener, and a child servlet context per DispatcherServlet (controllers, MVC beans). The child sees the parent's beans, not vice versa.

open as a page

What does initStrategies() do, and how does DispatcherServlet discover its special beans at startup?

level: seniorimportance: should knowfreq 55%

basics

~10 s

On context refresh, initStrategies() populates DispatcherServlet's strategy beans (HandlerMappings, HandlerAdapters, ViewResolvers, resolvers, etc.) by looking them up from the WebApplicationContext, falling back to defaults in DispatcherServlet.properties if none are defined.

open as a page

How does Spring Boot register and configure the DispatcherServlet? Walk through DispatcherServletAutoConfiguration.

level: principalimportance: should knowfreq 40%

basics

~10 s

Spring Boot's DispatcherServletAutoConfiguration creates the DispatcherServlet bean and a DispatcherServletRegistrationBean that registers it with the embedded servlet container, mapped to spring.mvc.servlet.path (default '/'), using the single Boot application context.

open as a page