How do I understand the DispatcherServlet in Spring MVC?

Spring MVC Series Banner

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:

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:

  1. The client sends an HTTP request.
  2. The servlet container forwards the request to the DispatcherServlet.
  3. The DispatcherServlet uses a HandlerMapping to find the appropriate controller method.
  4. The DispatcherServlet delegates handler execution to a HandlerAdapter.
  5. The controller processes the request and returns a logical view name.
  6. The DispatcherServlet uses a ViewResolver to resolve the view.
  7. The view renders the response using the model data.
  8. 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:

Spring MVC Dispatcher

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:

Plain-Text Response

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.

Simplified DipatcherServlet Processing Flow

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

How do I create my first Spring MVC application?

Spring MVC Series Banner

In the previous tutorial, we introduced Spring MVC and learned how the DispatcherServlet handles incoming HTTP requests.

In this tutorial, we will create our first working Spring MVC application using Java 25, Spring Framework 7.1.0, and Maven.

We will configure Spring MVC using Java classes instead of XML and deploy the application to Apache Tomcat 11.

We will not use Spring Boot in this example. This allows us to understand the basic components required to run a Spring MVC application.

1. Prerequisites

Before starting, make sure you have installed:

  • Java Development Kit (JDK) 25
  • Apache Maven 3.9 or later
  • Apache Tomcat 11
  • An IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code
  • Basic knowledge of Java classes and annotations

We will use the following technologies:

Technology Version Purpose
Java 25 Programming language
Spring Framework 7.1.0 Spring MVC framework
Jakarta Servlet API 6.1.0 Servlet interfaces
Apache Tomcat 11.x Web application server
Maven 3.9+ Build and dependency management

Tomcat 11 supports Jakarta Servlet 6.1, which is compatible with our application.

2. Create a Maven Project

Create a Maven project named spring-mvc-hello.

Use the following project information:

Group ID    : org.kodejava
Artifact ID : spring-mvc-hello
Version     : 1.0.0
Packaging   : war

Our application will have the following directory structure:

spring-mvc-hello/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── org/
        │       └── kodejava/
        │           └── springmvc/
        │               ├── config/
        │               │   ├── WebConfig.java
        │               │   └── WebAppInitializer.java
        │               └── controller/
        │                   └── HelloController.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── hello.jsp

We will create each file step by step.

3. Configure Maven

Open the pom.xml file and configure the project dependencies.

We need spring-webmvc to provide the Spring MVC functionality and jakarta.servlet-api for the servlet interfaces.

The servlet API uses the provided scope because Tomcat already supplies it when the application is deployed.

Here is the complete pom.xml:

<?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-hello</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-hello</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <release>25</release>
                </configuration>
            </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 war packaging type tells Maven to create a Web Application Archive that can be deployed to Tomcat.

The failOnMissingWebXml configuration allows us to build the application without a traditional web.xml deployment descriptor.

4. Create the Spring MVC Configuration

Next, create the WebConfig.java class in the config package.

package org.kodejava.springmvc.config;

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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import org.springframework.context.annotation.Bean;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }
}

Let’s understand the annotations and configuration.

@Configuration

The @Configuration annotation tells Spring that the class contains bean definitions and application configuration.

@EnableWebMvc

The @EnableWebMvc annotation enables Spring MVC configuration, including support for annotated controllers and request mappings.

@ComponentScan

The @ComponentScan annotation tells Spring where to find components such as classes annotated with @Controller.

In this example, Spring scans the org.kodejava.springmvc.controller package.

InternalResourceViewResolver

The InternalResourceViewResolver converts a logical view name into a JSP file path.

For example, when a controller returns:

return "hello";

Spring MVC resolves the view to:

/WEB-INF/views/hello.jsp

Placing JSP files under WEB-INF prevents users from accessing them directly through a browser. Instead, the pages are reached through Spring MVC controllers.

5. Register the DispatcherServlet

The DispatcherServlet is the central component of Spring MVC.

It receives HTTP requests and delegates them to the appropriate controller.

In older applications, developers commonly registered the DispatcherServlet using a web.xml file.

Modern Spring MVC applications can use Java configuration instead.

Create WebAppInitializer.java:

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[] { "/" };
    }
}

The AbstractAnnotationConfigDispatcherServletInitializer helps initialize Spring MVC when the servlet container starts the application.

We override three methods:

getRootConfigClasses()

Returns the configuration classes for the root application context. We return null because this simple application does not need a separate root context.

getServletConfigClasses()

Returns the Spring MVC configuration classes. In our application, this is WebConfig.class.

getServletMappings()

Defines which URL patterns are handled by the DispatcherServlet.

Using / allows the servlet to handle application requests while retaining the servlet container’s normal handling for JSP resources.

6. Create Your First Controller

Now we can create a controller that handles an HTTP request.

Create HelloController.java in the controller package.

package org.kodejava.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute(
                "message",
                "Hello, Spring MVC!"
        );

        return "hello";
    }
}

Let’s examine the controller.

@Controller

The @Controller annotation identifies the class as a Spring MVC controller.

Spring detects the class during component scanning and registers it as a bean.

@GetMapping

The @GetMapping("/hello") annotation maps HTTP GET requests to the hello() method.

When a user visits /hello, Spring MVC invokes this method.

Model

The Model interface allows us to pass data from the controller to the view.

In this example:

model.addAttribute("message", "Hello, Spring MVC!");

We add a model attribute named message.

The JSP page can access this attribute using Expression Language (EL).

Returning the View Name

The statement:

return "hello";

does not return the text hello to the browser.

Because the class uses @Controller, the returned string is interpreted as a logical view name.

Spring MVC uses our view resolver to locate hello.jsp.

7. Create the JSP View

Create the following file:

src/main/webapp/WEB-INF/views/hello.jsp

Add this HTML and JSP content:

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>My First Spring MVC Application</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f5f7fa;
            margin: 0;
            padding: 40px;
        }

        .container {
            max-width: 600px;
            margin: 60px auto;
            padding: 32px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            text-align: center;
        }

        h1 {
            color: #2563eb;
        }

        p {
            color: #475569;
        }
    </style>
</head>
<body>
    <main class="container">
        <h1>${message}</h1>
        <p>My first Spring MVC application is running!</p>
    </main>
</body>
</html>

The expression:

${message}

reads the message attribute added by the controller.

The JSP engine evaluates this expression and inserts the value into the generated HTML.

For this example, the message is a fixed string defined by the application. In applications that display user-provided content, use output escaping to prevent cross-site scripting vulnerabilities.

8. Build the Application

Open a terminal in the project directory.

Run:

mvn clean package

Maven will compile the Java classes, resolve dependencies, and package the application into a WAR file.

If the build succeeds, you should see a message similar to:

[INFO] BUILD SUCCESS

The generated file is located at:

target/spring-mvc-hello.war

9. Deploy the Application to Tomcat

Download and extract Apache Tomcat 11 if you have not installed it already.

Copy the generated WAR file into Tomcat’s webapps directory.

On Linux or macOS, for example:

cp target/spring-mvc-hello.war \
   /path/to/tomcat/webapps/

On Windows PowerShell:

Copy-Item `
    target/spring-mvc-hello.war `
    C:\apache-tomcat-11\webapps\

Adjust the Tomcat directory to match your installation.

Start Tomcat using its startup script.

Linux or macOS:

/path/to/tomcat/bin/startup.sh

Windows:

C:\apache-tomcat-11\bin\startup.bat

If Tomcat is already running with automatic deployment enabled, it may deploy the WAR without a restart.

10. Test the Application

Open your browser and visit:

http://localhost:8080/spring-mvc-hello/hello

You should see a page displaying:

Hello, Spring MVC!

My first Spring MVC application is running!

The page will use the CSS styles defined in our JSP file.

You can also inspect the HTTP response using curl:

curl -i http://localhost:8080/spring-mvc-hello/hello

A successful request returns an HTTP 200 response with HTML content.

11. Understanding the Request Flow

Let’s review what happens when the browser requests our page.

Spring MVC Request Flow Diagram

The request passes through these steps:

  1. The browser sends an HTTP GET request.
  2. Tomcat receives the request and forwards it to the DispatcherServlet.
  3. Spring MVC finds the controller method mapped to /hello.
  4. The controller adds the greeting message to the model.
  5. The controller returns the logical view name hello.
  6. The view resolver locates the JSP page.
  7. The JSP engine renders the page into HTML.
  8. Tomcat sends the generated HTML back to the browser.

This is the basic request-processing flow of a traditional Spring MVC application.

12. Common Problems

HTTP 404 Not Found

If the browser displays a 404 error, check the following:

  • The WAR file was deployed successfully.
  • The application context path is /spring-mvc-hello.
  • The controller uses @GetMapping("/hello").
  • The application started without deployment errors.

HTTP 500 Internal Server Error

A 500 error may indicate a problem with application configuration or JSP rendering.

Check the Tomcat logs in the logs directory for the underlying exception.

JSP File Cannot Be Found

Verify that your JSP file is located at:

src/main/webapp/WEB-INF/views/hello.jsp

Also verify that the prefix and suffix in WebConfig match the file location.

Java Version Errors

Make sure Maven and Tomcat are running with compatible Java versions.

Run:

java -version
mvn -version

The project is compiled for Java 25, so Tomcat must also run on Java 25 or a compatible newer Java runtime.

13. Summary

In this tutorial, we created our first Spring MVC application using Java configuration.

We learned how to:

  • Create a Maven-based Spring MVC project.
  • Configure Spring MVC with @EnableWebMvc.
  • Register the DispatcherServlet without web.xml.
  • Create a controller using @Controller and @GetMapping.
  • Pass data from a controller to a JSP view.
  • Configure an InternalResourceViewResolver.
  • Package the application as a WAR file.
  • Deploy and run the application on Apache Tomcat.

We now have a working Spring MVC application and understand how its main components work together.

In the next tutorial, How Does the DispatcherServlet Work in Spring MVC?, we will explore the internal request-processing mechanism, including handler mappings, handler adapters, and view resolution.

14. Maven Artifacts

The following Maven artifacts are required for this tutorial.

Spring Web MVC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.1.0</version>
</dependency>

Maven artifact: 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 artifact: 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>

Spring MVC automatically brings in several Spring dependencies through Maven’s transitive dependency management, so we do not need to declare each one manually.

References

How do I get started with Spring MVC?

Spring MVC Series Banner

Spring MVC is a web framework built on top of the Spring Framework. It helps developers create web applications and REST APIs using the Model-View-Controller (MVC) architectural pattern.

In this tutorial, we will introduce Spring MVC, explore its main components, and understand how an HTTP request is processed.

1. What is Spring MVC?

Spring MVC is part of the Spring Framework and provides a structured way to handle HTTP requests, process application logic, and generate responses.

It follows the Model-View-Controller pattern, which separates an application into three main responsibilities:

  • Model: Represents application data and business information.
  • View: Displays information to users, typically as HTML.
  • Controller: Receives HTTP requests and coordinates the application’s response.

This separation makes applications easier to develop, maintain, and test.

Spring MVC can also build REST APIs that return JSON instead of HTML.

2. How does Spring MVC work?

The central component of Spring MVC is the DispatcherServlet. It acts as a front controller that receives incoming HTTP requests and delegates them to the appropriate controller.

Spring MVC Request Flow Diagram

When a browser sends an HTTP request, Spring MVC performs the following steps:

  1. The DispatcherServlet receives the request.
  2. Spring MVC identifies the appropriate controller method.
  3. The controller processes the request, often calling application services.
  4. The controller returns data or a view name.
  5. Spring MVC generates an HTTP response.

For HTML pages, a view resolver can help locate the appropriate view template. For REST APIs, an HTTP message converter can serialize Java objects into JSON.

3. Creating a simple Spring MVC controller

Let’s look at a simple controller that returns a greeting.

package org.kodejava.springmvc;

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

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring MVC!";
    }
}

The example uses two important annotations:

  • @RestController tells Spring that the class handles web requests and writes return values directly to the HTTP response body.
  • @GetMapping("/hello") maps HTTP GET requests for /hello to the sayHello() method.

When the application is properly configured and running, accessing /hello returns:

Hello, Spring MVC!

This controller is only one part of a Spring MVC application. We still need to configure the application context and register the DispatcherServlet before it can handle requests.

We will implement these components in the next tutorial.

4. Spring MVC vs. Spring Boot

Spring MVC and Spring Boot are related, but they serve different purposes.

Spring MVC Spring Boot
Web application framework Application configuration and bootstrapping
Provides controllers and request mappings Provides auto-configuration
Can be configured manually Simplifies application setup
Supports HTML and REST APIs Can run Spring MVC with an embedded server

Spring Boot does not replace Spring MVC. Instead, Spring Boot can configure and run Spring MVC applications with less setup.

5. Summary

In this tutorial, we learned that Spring MVC is a web framework based on the MVC architectural pattern. We also introduced the DispatcherServlet, explored the request processing flow, and created a simple REST controller.

In the next tutorial, How do I create my first Spring MVC application?, we will build a complete application using Java configuration and Maven.

6. Maven Dependencies

This series uses Spring Framework 7.0.10, the latest stable 7.0 release verified for November 10, 2026. Spring Framework 7.1 is still in its release-candidate stage.

Add the following dependency to your Maven pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.0.10</version>
</dependency>

The dependency provides Spring MVC’s core functionality. A runnable web application will additionally need a compatible Jakarta Servlet environment, which we will configure later in this series.