In the previous tutorial, we created our first Spring MVC application using Java configuration, Maven, and Apache Tomcat. We registered a DispatcherServlet, created a controller, and displayed a JSP page in the browser.
But what actually happens when a browser sends an HTTP request to a Spring MVC application? How does Spring MVC know which controller method to execute? How does it generate an HTML page or write data directly to the HTTP response?
In this tutorial, we will explore the DispatcherServlet and the components involved in processing HTTP requests. We will also create a simple application that allows us to observe the request-processing flow.
1. What is the DispatcherServlet?
The DispatcherServlet is the central servlet in Spring MVC. It receives incoming HTTP requests mapped to it and coordinates the components responsible for processing those requests.
It implements a design pattern known as the Front Controller Pattern.
Instead of creating a separate servlet for every application feature, Spring MVC uses a central servlet to delegate requests to the appropriate controllers.
For example, consider the following application endpoints:
GET /products
GET /customers
GET /orders
Each endpoint may be handled by a different controller. However, all these requests can enter the application through the same DispatcherServlet.
The DispatcherServlet does not contain the application’s business logic. Its responsibility is to coordinate request processing.
2. The Front Controller Pattern
The Front Controller Pattern provides a centralized entry point for handling requests in a web application.
Without a front controller, we might need to create and register multiple servlets manually:
/products --> ProductServlet
/customers --> CustomerServlet
/orders --> OrderServlet
With Spring MVC, the requests are handled through the DispatcherServlet:

This approach allows Spring MVC to provide common functionality, such as request mapping, parameter conversion, exception handling, and response generation, without requiring developers to implement these features separately in every controller.
3. Main Components of the DispatcherServlet
The DispatcherServlet works with several components to process HTTP requests.
| Component |
Responsibility |
DispatcherServlet |
Coordinates request processing. |
HandlerMapping |
Finds the handler associated with an HTTP request. |
HandlerAdapter |
Executes the selected handler. |
HandlerInterceptor |
Intercepts requests before and after handler execution. |
Controller |
Processes application requests. |
Model |
Holds data to be displayed by a view. |
ViewResolver |
Resolves a logical view name into a view. |
View |
Renders the response using model data. |
HttpMessageConverter |
Reads and writes HTTP message bodies. |
HandlerExceptionResolver |
Handles exceptions during request processing. |
Let’s examine the most important components.
HandlerMapping
The HandlerMapping determines which handler should process an incoming request.
For annotation-based controllers, Spring MVC uses the RequestMappingHandlerMapping class.
Consider the following controller method:
@GetMapping("/hello")
public String hello() {
return "hello";
}
When Spring MVC receives a GET request for /hello, the handler mapping identifies the hello() method as the appropriate handler.
HandlerAdapter
After finding the handler, the DispatcherServlet delegates its execution to a HandlerAdapter.
For annotation-based controllers, Spring MVC uses RequestMappingHandlerAdapter.
This component performs several tasks, including:
- Resolving controller method arguments.
- Converting request parameters into Java types.
- Invoking the controller method.
- Processing the method’s return value.
For example:
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello!");
return "hello";
}
Spring MVC automatically provides the Model argument when invoking the method.
ViewResolver
A ViewResolver converts a logical view name into a view that can render the response.
For example, if a controller returns:
return "hello";
An InternalResourceViewResolver configured with a prefix of /WEB-INF/views/ and a suffix of .jsp resolves the view to:
/WEB-INF/views/hello.jsp
HttpMessageConverter
Not every Spring MVC request requires a view.
A controller method annotated with @ResponseBody can write its return value directly to the HTTP response.
@GetMapping("/message")
@ResponseBody
public String message() {
return "Hello, Spring MVC!";
}
Spring MVC uses an appropriate HttpMessageConverter to write the returned value to the response body.
In this example, the StringHttpMessageConverter can write the returned string as plain text.
For Java objects, Spring MVC can use a JSON message converter when the necessary JSON library is available.
HandlerExceptionResolver
The HandlerExceptionResolver provides a mechanism for handling exceptions that occur during request processing.
For example, it can help Spring MVC convert an exception into an appropriate HTTP error response or an error view.
We will explore exception handling in more detail in a later tutorial.
4. Understanding the Request Processing Flow
A typical Spring MVC request that returns an HTML page follows these steps:
- The client sends an HTTP request.
- The servlet container forwards the request to the
DispatcherServlet.
- The
DispatcherServlet uses a HandlerMapping to find the appropriate controller method.
- The
DispatcherServlet delegates handler execution to a HandlerAdapter.
- The controller processes the request and returns a logical view name.
- The
DispatcherServlet uses a ViewResolver to resolve the view.
- The view renders the response using the model data.
- The response is returned to the client.
When a controller uses @ResponseBody, the handler adapter can write the response through an HTTP message converter. In this case, the view resolution and rendering steps are not required.
5. Creating the Example Application
To understand how these components work together, we will create a Spring MVC application with two endpoints:
/hello — returns an HTML page using a JSP view.
/message — returns a plain-text response.
We will also register a simple interceptor to observe the request-processing lifecycle.
This example uses the following technologies:
| Technology |
Version |
| Java |
25 |
| Spring Framework |
7.1.0 |
| Jakarta Servlet API |
6.1.0 |
| Apache Tomcat |
11.x |
| Apache Maven |
3.9 or later |
We will continue using traditional Spring MVC without Spring Boot.
6. Project Structure
Create a Maven project named spring-mvc-dispatcher.
The project has the following directory structure:
spring-mvc-dispatcher/
├── pom.xml
└── src/
└── main/
├── java/
│ └── org/kodejava/springmvc/
│ ├── config/
│ │ ├── WebConfig.java
│ │ └── WebAppInitializer.java
│ ├── controller/
│ │ └── HelloController.java
│ └── interceptor/
│ └── RequestLoggingInterceptor.java
└── webapp/
└── WEB-INF/
└── views/
└── hello.jsp
7. Configuring Maven
Create the following pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.kodejava</groupId>
<artifactId>spring-mvc-dispatcher</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>7.1.0</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-dispatcher</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
The spring-webmvc dependency provides the Spring MVC infrastructure.
The Jakarta Servlet API uses the provided scope because Apache Tomcat provides the servlet implementation at runtime.
8. Registering the DispatcherServlet
Create the WebAppInitializer.java class.
package org.kodejava.springmvc.config;
import org.springframework.web.servlet.support
.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
When Tomcat starts the application, Spring’s servlet initialization mechanism discovers this class and registers the DispatcherServlet.
The getServletConfigClasses() method specifies the configuration class used by the servlet’s application context.
The getServletMappings() method maps the servlet to /.
This mapping allows the DispatcherServlet to handle our application endpoints while JSP requests can still be handled by the container’s JSP servlet.
9. Creating a Request Logging Interceptor
To observe request processing, we will implement the HandlerInterceptor interface.
Create the RequestLoggingInterceptor.java class.
package org.kodejava.springmvc.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jspecify.annotations.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class RequestLoggingInterceptor
implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) {
System.out.println("[1] preHandle");
System.out.printf(
" Request: %s %s%n",
request.getMethod(),
request.getRequestURI()
);
if (handler instanceof HandlerMethod method) {
System.out.printf(
" Handler: %s.%s()%n",
method.getBeanType().getSimpleName(),
method.getMethod().getName()
);
}
return true;
}
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
@Nullable ModelAndView modelAndView) {
System.out.println("[3] postHandle");
if (modelAndView != null) {
System.out.println(
" View: " + modelAndView.getViewName()
);
} else {
System.out.println(" No ModelAndView");
}
}
@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
@Nullable Exception ex) {
System.out.println("[4] afterCompletion");
System.out.println(
" HTTP status: " + response.getStatus()
);
}
}
The HandlerInterceptor interface provides three callback methods.
preHandle()
The preHandle() method is called after Spring MVC selects a handler but before the handler is executed.
Returning true allows request processing to continue.
Returning false stops the normal handler execution chain.
postHandle()
The postHandle() method is called after successful handler execution.
For a controller that returns a view, this method is normally called before the view is rendered.
The ModelAndView argument contains the model and view information when available.
For a controller that writes directly to the response body, the argument is normally null.
afterCompletion()
The afterCompletion() method is called when request processing completes, provided the interceptor’s preHandle() method completed successfully and returned true.
This method is useful for cleanup and request logging.
In this example, we use System.out.println() to keep the code simple. Production applications should use a proper logging framework.
10. Configuring Spring MVC
Create the WebConfig.java class.
package org.kodejava.springmvc.config;
import org.kodejava.springmvc.interceptor.RequestLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver viewResolver() {
var resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestLoggingInterceptor())
.addPathPatterns("/hello", "/message");
}
}
The @EnableWebMvc annotation enables Spring MVC infrastructure, including handler mappings, handler adapters, and message converters.
The viewResolver() method configures JSP view resolution.
The addInterceptors() method registers our custom interceptor for the /hello and /message endpoints.
The interceptor allows us to observe the request-processing lifecycle without modifying the DispatcherServlet itself.
11. Creating the Controller
Create the HelloController.java class.
package org.kodejava.springmvc.controller;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
System.out.println("[2] Controller: hello()");
model.addAttribute(
"message",
"Hello from DispatcherServlet!"
);
return "hello";
}
@GetMapping(
value = "/message",
produces = MediaType.TEXT_PLAIN_VALUE
)
@ResponseBody
public String message() {
System.out.println("[2] Controller: message()");
return "This response does not require a view.";
}
}
The controller contains two methods that demonstrate different response-processing mechanisms.
The hello() method adds data to the model and returns a logical view name.
The message() method uses @ResponseBody to write a string directly to the HTTP response.
Although both methods return a String, Spring MVC processes their return values differently.
| Method |
Return value interpretation |
hello() |
Logical view name |
message() |
HTTP response body |
The @ResponseBody annotation is what makes the difference.
12. Creating the JSP View
Create the hello.jsp file under the src/main/webapp/WEB-INF/views directory.
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spring MVC DispatcherServlet</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f8fafc;
color: #1e293b;
margin: 40px;
}
main {
max-width: 640px;
margin: 60px auto;
padding: 32px;
background: white;
border: 1px solid #e2e8f0;
border-radius: 12px;
}
h1 {
color: #2563eb;
}
code {
background: #f1f5f9;
padding: 3px 6px;
border-radius: 4px;
}
</style>
</head>
<body>
<main>
<h1>${message}</h1>
<p>
This page is rendered using a JSP view.
</p>
<p>
The request is processed by the
<code>DispatcherServlet</code>.
</p>
</main>
</body>
</html>
The ${message} expression retrieves the model attribute provided by the controller.
Because the message is a fixed application-defined string, this example does not involve untrusted user input. When displaying user-provided values, make sure to escape the output appropriately.
13. Building and Running the Application
Open a terminal in the project directory and execute:
mvn clean package
After Maven completes the build, the generated WAR file is located at:
target/spring-mvc-dispatcher.war
Copy the WAR file into the webapps directory of Apache Tomcat 11.
On Linux or macOS:
cp target/spring-mvc-dispatcher.war \
"$CATALINA_HOME/webapps/"
On Windows PowerShell:
Copy-Item target/spring-mvc-dispatcher.war `
"$env:CATALINA_HOME\webapps\"
These commands assume that the CATALINA_HOME environment variable points to your Tomcat installation directory.
Start Tomcat in foreground mode so that you can observe the interceptor output directly in the terminal.
On Linux or macOS:
"$CATALINA_HOME/bin/catalina.sh" run
On Windows PowerShell:
& "$env:CATALINA_HOME\bin\catalina.bat" run
Make sure Tomcat is running with Java 25 because our application is compiled for Java 25.
14. Testing the HTML Response
Open your browser and visit:
http://localhost:8080/spring-mvc-dispatcher/hello
The browser should display:

The Tomcat console should contain output similar to the following:
[1] preHandle
Request: GET /spring-mvc-dispatcher/hello
Handler: HelloController.hello()
[2] Controller: hello()
[3] postHandle
View: hello
[4] afterCompletion
HTTP status: 200
The output shows that Spring MVC has selected the hello() method before calling the interceptor’s preHandle() method.
The controller is then executed, followed by the postHandle() method.
After the JSP view has been rendered, the afterCompletion() method is called.
15. Testing the Plain-Text Response
Open the following URL:
http://localhost:8080/spring-mvc-dispatcher/message
The browser should display:

The Tomcat console should contain output similar to the following:
[1] preHandle
Request: GET /spring-mvc-dispatcher/message
Handler: HelloController.message()
[2] Controller: message()
[3] postHandle
No ModelAndView
[4] afterCompletion
HTTP status: 200
Notice that the postHandle() method does not receive a ModelAndView object.
This happens because the controller uses @ResponseBody.
The handler adapter processes the return value using an HTTP message converter rather than returning a logical view name to the DispatcherServlet.
We can also test this endpoint using curl:
curl -i http://localhost:8080/spring-mvc-dispatcher/message
The response should be similar to:
HTTP/1.1 200
Content-Type: text/plain;charset=ISO-8859-1
This response does not require a view.
The actual response headers, including the character encoding, may vary depending on the Spring MVC and servlet container configuration.
16. Comparing View Rendering and Response Body Processing
Our application demonstrates two common ways of generating HTTP responses.
View Rendering and Response Body Processing
When a controller returns a logical view name, the processing flow includes view resolution and rendering.
When a controller uses @ResponseBody, the response is generated through an HTTP message converter during handler adapter execution.

These diagrams are simplified. The DispatcherServlet coordinates the components rather than simply passing the request from one component to the next.
The important difference is that response body processing does not require a ViewResolver.
This mechanism is commonly used when building REST APIs.
17. What Happens When No Handler Is Found?
Try accessing an endpoint that does not exist:
http://localhost:8080/spring-mvc-dispatcher/unknown
The application should return an HTTP 404 response.
This happens because Spring MVC cannot find a handler for the requested path.
Similarly, sending a POST request to an endpoint that only supports GET normally produces an HTTP 405 response.
curl -i -X POST \
http://localhost:8080/spring-mvc-dispatcher/hello
Expected HTTP status:
405 Method Not Allowed
These examples demonstrate that Spring MVC considers both the request path and the HTTP method when selecting a handler.
18. Summary
In this tutorial, we learned how the DispatcherServlet coordinates HTTP request processing in Spring MVC.
We explored the following concepts:
- The Front Controller Pattern.
- The role of the
DispatcherServlet.
- Finding controllers using
HandlerMapping.
- Executing controllers using
HandlerAdapter.
- Observing request processing using
HandlerInterceptor.
- Rendering HTML pages using
ViewResolver.
- Writing response bodies using
HttpMessageConverter.
- Understanding the difference between view names and response bodies.
- Handling requests that do not match a controller.
Understanding the DispatcherServlet provides a strong foundation for learning more advanced Spring MVC features.
In the next tutorial, How do I configure Spring MVC using Java configuration?, we will explore WebMvcConfigurer, application context configuration, static resources, and other configuration options in more detail.
19. Maven Artifacts
The following Maven artifacts are required for this example.
Spring Web MVC
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>7.1.0</version>
</dependency>
Maven coordinates:
org.springframework:spring-webmvc:7.1.0
Jakarta Servlet API
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
Maven coordinates:
jakarta.servlet:jakarta.servlet-api:6.1.0
Maven Compiler Plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
Maven WAR Plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.5.0</version>
</plugin>
Other required Spring modules and JSpecify annotations are available through Spring’s transitive dependencies.
References