Mastering SpringBoot Web Core: How DispatcherServlet Coordinates Requests

This article explains how SpringBoot’s DispatcherServlet acts as the central dispatcher of the Web module, detailing its role and the surrounding core components—HandlerMapping, HandlerAdapter, HandlerExceptionResolver, ViewResolver, and HttpMessageConverter—along with practical code examples and common pitfalls.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop
Mastering SpringBoot Web Core: How DispatcherServlet Coordinates Requests

Many developers are familiar with writing Controllers and Services but often overlook the underlying components that process an HTTP request in a SpringBoot Web application. This article starts with DispatcherServlet, the central dispatcher of the SpringBoot Web module, and then walks through each core component, their responsibilities, and how they work together.

What is DispatcherServlet?

DispatcherServlet is a subclass of the standard Servlet and the core of Spring MVC. When the spring-boot-starter-web dependency is added, SpringBoot automatically configures a DispatcherServlet that handles all incoming URLs (mapped to /* by default).

Example code to verify the auto‑configuration:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class WebCoreApplication implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(WebCoreApplication.class, args);
    }

    // Verify DispatcherServlet auto‑configuration (optional)
    @Bean
    public DispatcherServlet dispatcherServlet() {
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        System.out.println("DispatcherServlet auto‑configured: " + dispatcherServlet);
        return dispatcherServlet;
    }
}

DispatcherServlet’s core function is to receive every HTTP request, delegate it to the appropriate components, and return the final response—much like a project manager coordinating tasks.

⚠️ Common issue: If a Controller endpoint is unreachable, the most likely cause is that DispatcherServlet was not correctly auto‑configured (e.g., missing spring-boot-starter-web or missing @SpringBootApplication on the main class).

SpringBoot Web Core Components

1. HandlerMapping

Purpose: Map a request URL to the corresponding Controller method (Handler). The default implementation is RequestMappingHandlerMapping, which supports annotations such as @RequestMapping, @GetMapping, and @PostMapping.

Custom configuration example:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class WebConfig {
    // Custom HandlerMapping (default is auto‑configured, demo only)
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping();
        // Add a common prefix to all endpoints
        handlerMapping.setPrefix("/api");
        return handlerMapping;
    }
}

If interceptors are defined, HandlerMapping also binds them to the matched Handler so that requests pass through interceptors before reaching the Controller.

2. HandlerAdapter

Purpose: Invoke the Handler (Controller method) and handle method parameters and return values. Different Handlers may have different signatures, so HandlerAdapter adapts them to a uniform invocation process. The default is RequestMappingHandlerAdapter.

Custom configuration example:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

@Configuration
public class WebConfig {
    // Verify HandlerAdapter role (custom argument resolver, simplified)
    @Bean
    public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
        // Add custom argument resolvers here if needed
        System.out.println("HandlerAdapter initialized, handling parameter parsing and method invocation");
        return adapter;
    }
}

⚠️ If a Controller method’s parameter binding fails (e.g., malformed JSON for @RequestBody), the failure is reported by HandlerAdapter and results in a 400 Bad Request.

3. HandlerExceptionResolver

Purpose: Catch exceptions thrown during request processing (from Controllers, interceptors, etc.) and produce a unified error response instead of a raw stack trace.

Typical implementation using @RestControllerAdvice:

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // Handle all uncaught exceptions
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        e.printStackTrace();
        return Result.fail(500, "Server error: " + e.getMessage());
    }

    // Handle parameter binding errors (triggered by HandlerAdapter failures)
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<?> handleIllegalArgumentException(IllegalArgumentException e) {
        return Result.fail(400, "Parameter error: " + e.getMessage());
    }
}

4. ViewResolver

Purpose: Resolve a view name returned by a Controller into an actual view resource (e.g., a JSP page). In front‑end‑separated projects the Controller usually returns JSON, so ViewResolver is rarely used; it is essential for traditional MVC applications.

Configuration for a JSP project:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebConfig {
    // Traditional JSP project, configure ViewResolver
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

SpringBoot’s default ViewResolver is InternalResourceViewResolver, suitable for JSP. For JSON‑first APIs you can ignore it.

5. HttpMessageConverter

Purpose: Convert the request body to a Java object and convert a Java object to the response body (e.g., JSON). It underlies JSON formatting, date formatting, and other data‑binding concerns.

Customizing the default MappingJackson2HttpMessageConverter to apply a global date format and serialize Long values as strings (to avoid JavaScript precision loss):

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jsonConverter());
    }

    @Bean
    public MappingJackson2HttpMessageConverter jsonConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();

        // 1. Global date formatting
        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        // 2. Long to String, solve JS precision loss
        SimpleModule longModule = new SimpleModule();
        longModule.addSerializer(Long.class, ToStringSerializer.instance);
        longModule.addSerializer(Long.TYPE, ToStringSerializer.instance);

        objectMapper.registerModule(timeModule);
        objectMapper.registerModule(longModule);
        converter.setObjectMapper(objectMapper);
        return converter;
    }
}

Complete HTTP Request Execution Chain

Client sends an HTTP request (e.g., GET /user/1) which first reaches the embedded Tomcat container.

Tomcat forwards the request to SpringBoot’s DispatcherServlet (all requests pass through it).

DispatcherServlet uses HandlerMapping to locate the matching Controller method (Handler).

DispatcherServlet invokes HandlerAdapter, which calls the located Controller method and executes business logic (Service, Mapper, etc.).

The Controller returns a result (Java object or view name); HandlerAdapter passes this result back to DispatcherServlet.

If the result is a Java object (typical for JSON APIs), DispatcherServlet calls HttpMessageConverter to serialize the object to JSON.

If the result is a view name (traditional MVC), DispatcherServlet calls ViewResolver to resolve the view.

If an exception occurs during processing, HandlerExceptionResolver captures it and returns a unified error format.

DispatcherServlet sends the final response (JSON or view) back to Tomcat, which returns it to the client.

Practical Development Tips

DispatcherServlet auto‑configuration: adding spring-boot-starter-web automatically registers a DispatcherServlet with a default mapping of /*; no manual configuration is required.

Component customization: if the default behavior does not meet requirements (e.g., custom date format, custom exception handling), you can override the corresponding component via a @Configuration class.

Request interception order: Filter operates at the Tomcat level before DispatcherServlet; Interceptor runs after DispatcherServlet but before the Controller. Do not confuse their execution order.

Parameter binding failures: when a Controller method’s parameters cannot be bound (e.g., malformed JSON), check the HttpMessageConverter configuration.

Conclusion

SpringBoot’s Web module revolves around DispatcherServlet, which coordinates HandlerMapping, HandlerAdapter, HttpMessageConverter, ViewResolver, and HandlerExceptionResolver to complete the full request‑receive‑process‑respond cycle. Mastering these components helps resolve everyday development issues and prepares you for interview questions on Spring MVC internals.

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.

SpringBootSpring MVCDispatcherServletHandlerMappingHandlerAdapterHttpMessageConverterViewResolver
Java Tech Workshop
Written by

Java Tech Workshop

Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.

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.