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.
Browser
|
| GET /spring-mvc-hello/hello
v
Apache Tomcat
|
v
DispatcherServlet
|
v
HelloController
|
| model.addAttribute(...)
| return "hello"
v
View Resolver
|
v
/WEB-INF/views/hello.jsp
|
v
HTML Response
|
v
Browser
The request passes through these steps:
- The browser sends an HTTP GET request.
- Tomcat receives the request and forwards it to the
DispatcherServlet. - Spring MVC finds the controller method mapped to
/hello. - The controller adds the greeting message to the model.
- The controller returns the logical view name
hello. - The view resolver locates the JSP page.
- The JSP engine renders the page into HTML.
- 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
DispatcherServletwithoutweb.xml. - Create a controller using
@Controllerand@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.
