Understanding Spring’s DispatcherServlet: From XML Config to Spring Boot Auto‑Configuration

This article explains the role of Spring's DispatcherServlet, details its traditional web.xml configuration, walks through its request‑handling workflow, and shows how Spring Boot automatically configures and registers the servlet using concise code examples and annotations.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Understanding Spring’s DispatcherServlet: From XML Config to Spring Boot Auto‑Configuration

DispatcherServlet Overview

DispatcherServlet implements the Front‑Controller pattern for Spring Web MVC, serving as a centralized entry point that delegates requests to appropriate handlers while integrating seamlessly with the Spring IoC container.

Key Responsibilities

File upload parsing via MultipartResolver when the request is multipart.

Mapping requests to handlers using HandlerMapping, producing a HandlerExecutionChain that includes the handler and any HandlerInterceptor s.

Supporting various handler types through HandlerAdapter.

Resolving logical view names to concrete view implementations via ViewResolver.

Locale resolution.

View rendering.

Exception handling through HandlerExceptionResolver.

Traditional XML Configuration

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcherServlet-servlet.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

In this classic setup the servlet is declared in web.xml, where the name, class, initialization parameters, and URL mapping are defined.

DispatcherServlet Processing Flow

When a request matches the servlet mapping, DispatcherServlet performs the following steps:

Binds the WebApplicationContext to the request (default attribute name DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE).

Attaches a locale resolver for internationalization.

Attaches a theme resolver if theming is used.

Detects multipart requests and wraps them in MultipartHttpServletRequest when a multipart resolver is present.

Locates the appropriate handler and executes the associated interceptor chain, controller, and model preparation.

Uses configured ViewResolver s to render the view if a model is returned; otherwise the view is omitted.

Relevant Source Code

Core part of DispatcherServlet.doService:

protected void doService(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    // ...
    request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
    // ...
}

Initialization of strategies performed during servlet startup:

protected void initStrategies(ApplicationContext context) {
    initMultipartResolver(context);
    initLocaleResolver(context);
    initThemeResolver(context);
    initHandlerMappings(context);
    initHandlerAdapters(context);
    initHandlerExceptionResolvers(context);
    initRequestToViewNameTranslator(context);
    initViewResolvers(context);
    initFlashMapManager(context);
}

Spring Boot Auto‑Configuration

Spring Boot configures DispatcherServlet via DispatcherServletAutoConfiguration:

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(DispatcherServlet.class)
@AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class)
public class DispatcherServletAutoConfiguration {
    ...
}

The annotations specify that the configuration applies only to servlet‑based web applications, requires the DispatcherServlet class on the classpath, and runs with the highest precedence after the servlet container is set up.

DispatcherServlet Bean Creation

@Configuration(proxyBeanMethods = false)
@Conditional(DefaultDispatcherServletCondition.class)
@ConditionalOnClass(ServletRegistration.class)
@EnableConfigurationProperties({ HttpProperties.class, WebMvcProperties.class })
protected static class DispatcherServletConfiguration {

  @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
  public DispatcherServlet dispatcherServlet(HttpProperties httpProperties, WebMvcProperties webMvcProperties) {
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());
    dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());
    dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());
    dispatcherServlet.setEnableLoggingRequestDetails(httpProperties.isLogRequestDetails());
    return dispatcherServlet;
  }

  @Bean
  @ConditionalOnBean(MultipartResolver.class)
  @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
  public MultipartResolver multipartResolver(MultipartResolver resolver) {
    // Detect if the user has created a MultipartResolver but named it incorrectly
    return resolver;
  }
}

This configuration creates the DispatcherServlet instance, sets common properties from WebMvcProperties and HttpProperties, and ensures a correctly named multipart resolver.

Default DispatcherServlet Condition

@Order(Ordered.LOWEST_PRECEDENCE - 10)
private static class DefaultDispatcherServletCondition extends SpringBootCondition {

  @Override
  public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet");
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    List<String> dispatchServletBeans = Arrays.asList(
        beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false));
    if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
      return ConditionOutcome.noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));
    }
    if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
      return ConditionOutcome.noMatch(message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));
    }
    if (dispatchServletBeans.isEmpty()) {
      return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll());
    }
    return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans")
        .items(Style.QUOTE, dispatchServletBeans)
        .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));
  }
}

The condition ensures that auto‑configuration only creates a DispatcherServlet when no bean named dispatcherServlet already exists.

Servlet Registration Configuration

@Configuration(proxyBeanMethods = false)
@Conditional(DispatcherServletRegistrationCondition.class)
@ConditionalOnClass(ServletRegistration.class)
@EnableConfigurationProperties(WebMvcProperties.class)
@Import(DispatcherServletConfiguration.class)
protected static class DispatcherServletRegistrationConfiguration {

  @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
  @ConditionalOnBean(value = DispatcherServlet.class, name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
  public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet,
      WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) {
    DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet,
        webMvcProperties.getServlet().getPath());
    registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
    registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
    multipartConfig.ifAvailable(registration::setMultipartConfig);
    return registration;
  }
}

This class registers the DispatcherServlet with the servlet container, applying the path and load‑on‑startup settings defined in WebMvcProperties.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

springSpringBootautoconfigurationDispatcherServletWeb MVC
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.