How Do I Create My First Spring MVC Application?

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:

  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 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.

How Do I Build REST APIs with Spring MVC?

Building REST APIs with Spring MVC

In Spring MVC, you build REST APIs by defining controller classes that map HTTP requests to Java methods. In modern Spring Boot applications, this is usually done with @RestController.

A typical REST API is organized like this:

HTTP Request
    ↓
Controller
    ↓
Service
    ↓
Repository
    ↓
Database

Each layer has a clear responsibility:

Layer Responsibility
Controller Handles HTTP requests and responses
Service Contains business logic
Repository Handles database access
Entity Represents database tables
DTO Represents API request/response data

1. Add the Spring Web Dependency

For Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

If you need validation:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

If you use JPA:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2. Create a REST Controller

Use @RestController for REST APIs. It combines @Controller and @ResponseBody, meaning returned objects are written directly to the HTTP response, usually as JSON.

package com.example.demo.user;

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

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    public String hello() {
        return "Hello, REST API!";
    }
}

Calling:

GET /api/hello

returns:

Hello, REST API!

3. Design Resource-Based URLs

REST APIs should use nouns for resources and HTTP methods for actions.

Good:

GET    /api/users
GET    /api/users/1
POST   /api/users
PUT    /api/users/1
DELETE /api/users/1

Avoid action-style URLs like:

/api/getUsers
/api/createUser
/api/deleteUser

The HTTP method already describes the operation.


4. Create DTOs for Request and Response Bodies

Avoid exposing database entities directly from your API. Use DTOs instead.

package com.example.demo.user;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

public record CreateUserRequest(
        @NotBlank String name,
        @NotBlank @Email String email
) {
}
package com.example.demo.user;

public record UserResponse(
        Long id,
        String name,
        String email
) {
}

DTOs keep your API contract separate from your database model.


5. Create REST Endpoints

A controller for basic CRUD operations might look like this:

package com.example.demo.user;

import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<UserResponse> findAll() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public UserResponse findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public UserResponse create(@Valid @RequestBody CreateUserRequest request) {
        return userService.create(request);
    }

    @PutMapping("/{id}")
    public UserResponse update(
            @PathVariable Long id,
            @Valid @RequestBody CreateUserRequest request
    ) {
        return userService.update(id, request);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        userService.delete(id);
    }
}

Key annotations:

Annotation Purpose
@RestController Marks the class as a REST controller
@RequestMapping Defines a base URL
@GetMapping Handles HTTP GET
@PostMapping Handles HTTP POST
@PutMapping Handles HTTP PUT
@DeleteMapping Handles HTTP DELETE
@PathVariable Reads values from the URL path
@RequestBody Reads JSON from the request body
@Valid Triggers Jakarta Bean Validation
@ResponseStatus Sets the HTTP response status

6. Put Business Logic in a Service

Controllers should stay thin. Put business rules in a service class.

package com.example.demo.user;

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    public List<UserResponse> findAll() {
        // Load users from repository
        return List.of();
    }

    public UserResponse findById(Long id) {
        // Find user by id
        return new UserResponse(id, "Alice", "[email protected]");
    }

    public UserResponse create(CreateUserRequest request) {
        // Create user
        return new UserResponse(1L, request.name(), request.email());
    }

    public UserResponse update(Long id, CreateUserRequest request) {
        // Update user
        return new UserResponse(id, request.name(), request.email());
    }

    public void delete(Long id) {
        // Delete user
    }
}

In a real application, the service would call a repository.


7. Use Spring Data JPA for Persistence

If your API stores data in a database, create an entity and repository.

package com.example.demo.user;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;
}
package com.example.demo.user;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

By extending JpaRepository, you automatically get methods like:

findAll();
findById(id);
save(entity);
delete(entity);
existsById(id);

8. Return Proper HTTP Status Codes

Use status codes that match the result:

Situation Status
Successful read 200 OK
Created resource 201 Created
Deleted resource 204 No Content
Invalid request 400 Bad Request
Missing resource 404 Not Found
Conflict 409 Conflict
Server error 500 Internal Server Error

For creation, you can also return a Location header:

package com.example.demo.user;

import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<UserResponse> create(
            @Valid @RequestBody CreateUserRequest request,
            UriComponentsBuilder uriBuilder
    ) {
        UserResponse response = userService.create(request);

        URI location = uriBuilder
                .path("/api/users/{id}")
                .buildAndExpand(response.id())
                .toUri();

        return ResponseEntity.created(location).body(response);
    }
}

9. Handle Errors Globally

Use @RestControllerAdvice to return consistent JSON errors.

package com.example.demo.exception;

import java.time.Instant;
import java.util.List;

public record ApiError(
        int status,
        String error,
        String message,
        String path,
        Instant timestamp,
        List<FieldErrorDetail> fieldErrors
) {
    public record FieldErrorDetail(
            String field,
            String message
    ) {
    }
}
package com.example.demo.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}
package com.example.demo.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiError handleNotFound(
            ResourceNotFoundException ex,
            HttpServletRequest request
    ) {
        return new ApiError(
                404,
                "Not Found",
                ex.getMessage(),
                request.getRequestURI(),
                Instant.now(),
                List.of()
        );
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiError handleValidation(
            MethodArgumentNotValidException ex,
            HttpServletRequest request
    ) {
        List<ApiError.FieldErrorDetail> fieldErrors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> new ApiError.FieldErrorDetail(
                        error.getField(),
                        error.getDefaultMessage()
                ))
                .toList();

        return new ApiError(
                400,
                "Bad Request",
                "Validation failed",
                request.getRequestURI(),
                Instant.now(),
                fieldErrors
        );
    }
}

10. Test Your API

Example using curl:

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","email":"[email protected]"}'

Get all users:

curl http://localhost:8080/api/users

Get one user:

curl http://localhost:8080/api/users/1

Update a user:

curl -X PUT http://localhost:8080/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice Smith","email":"[email protected]"}'

Delete a user:

curl -X DELETE http://localhost:8080/api/users/1

11. Add Pagination for List Endpoints

For large collections, avoid returning everything at once.

package com.example.demo.user;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public Page<UserResponse> findAll(Pageable pageable) {
        return userService.findAll(pageable);
    }
}

Then clients can call:

GET /api/users?page=0&size=10
GET /api/users?page=0&size=10&sort=name,asc

Recommended Checklist

When building REST APIs with Spring MVC:

  • Use @RestController.
  • Use resource-based URLs like /api/users.
  • Use HTTP methods correctly: GET, POST, PUT, PATCH, DELETE.
  • Keep controllers thin.
  • Put business logic in services.
  • Use repositories for database access.
  • Use DTOs instead of exposing entities.
  • Validate request bodies with jakarta.validation.
  • Handle errors globally with @RestControllerAdvice.
  • Return correct HTTP status codes.
  • Add pagination for collection endpoints.
  • Use jakarta.* imports in modern Spring Boot applications.

A clean REST API usually follows this shape:

Controller → Service → Repository → Database

That structure keeps your Spring MVC API easier to test, maintain, and evolve.

How do I handle exceptions globally in Spring MVC?

In Spring MVC, handle exceptions globally by creating a class annotated with @ControllerAdvice or @RestControllerAdvice and adding methods annotated with @ExceptionHandler.

For REST APIs, prefer @RestControllerAdvice, because it combines @ControllerAdvice and @ResponseBody, so returned objects are serialized as JSON automatically.

package com.example.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleResourceNotFoundException(
            ResourceNotFoundException ex
    ) {
        ErrorResponse error = new ErrorResponse(
                HttpStatus.NOT_FOUND.value(),
                ex.getMessage()
        );

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(
            Exception ex
    ) {
        ErrorResponse error = new ErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "An unexpected error occurred"
        );

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}

Example error response DTO:

package com.example.demo.exception;

import java.time.Instant;

public record ErrorResponse(
        int status,
        String message,
        Instant timestamp
) {
    public ErrorResponse(int status, String message) {
        this(status, message, Instant.now());
    }
}

Example custom exception:

package com.example.demo.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

Then you can throw exceptions from controllers or services:

throw new ResourceNotFoundException("User not found");

Spring will automatically route that exception to the matching @ExceptionHandler.

Common handlers you may want to add:

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationException(
        MethodArgumentNotValidException ex
) {
    ErrorResponse error = new ErrorResponse(
            HttpStatus.BAD_REQUEST.value(),
            "Validation failed"
    );

    return ResponseEntity.badRequest().body(error);
}

Use:

  • @RestControllerAdvice for REST APIs returning JSON.
  • @ControllerAdvice for MVC apps returning views or when you manually use ResponseEntity.
  • Specific exception handlers before generic ones.
  • A final @ExceptionHandler(Exception.class) as a fallback.

How do I validate form data in Spring?

In Spring MVC, the standard way to validate form data is to use Jakarta Bean Validation annotations on a form/DTO object, then check validation results in your controller with BindingResult.

Since your project uses Jakarta EE, use jakarta.validation.* imports.

1. Add validation annotations to your form object

Example form/DTO:

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class UserForm {

    @NotBlank(message = "Name is required")
    @Size(max = 100, message = "Name must be at most 100 characters")
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Please enter a valid email address")
    private String email;

    @NotBlank(message = "Password is required")
    @Size(min = 8, message = "Password must be at least 8 characters")
    private String password;

    // getters and setters
}

With Lombok:

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserForm {

    @NotBlank(message = "Name is required")
    @Size(max = 100, message = "Name must be at most 100 characters")
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Please enter a valid email address")
    private String email;

    @NotBlank(message = "Password is required")
    @Size(min = 8, message = "Password must be at least 8 characters")
    private String password;
}

2. Use @Valid in your controller

import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class UserController {

    @GetMapping("/register")
    public String showRegisterForm(Model model) {
        model.addAttribute("userForm", new UserForm());
        return "register";
    }

    @PostMapping("/register")
    public String register(
            @Valid UserForm userForm,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            return "register";
        }

        // Save user or call service layer here
        return "redirect:/register/success";
    }
}

Important: BindingResult must come immediately after the validated object.

Correct:

public String register(@Valid UserForm userForm, BindingResult bindingResult)

Incorrect:

public String register(@Valid UserForm userForm, Model model, BindingResult bindingResult)

3. Display errors in Thymeleaf

If you use Thymeleaf:

<form th:action="@{/register}" th:object="${userForm}" method="post">
    <div>
        <label>Name</label>
        <input type="text" th:field="*{name}">
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
    </div>

    <div>
        <label>Email</label>
        <input type="email" th:field="*{email}">
        <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
    </div>

    <div>
        <label>Password</label>
        <input type="password" th:field="*{password}">
        <span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span>
    </div>

    <button type="submit">Register</button>
</form>

4. Common validation annotations

@NotNull
@NotBlank
@NotEmpty
@Size(min = 2, max = 100)
@Min(18)
@Max(120)
@Email
@Pattern(regexp = "...")
@Past
@Future
@Positive
@PositiveOrZero

Use:

  • @NotNull for any value that must not be null
  • @NotBlank for strings that must contain non-whitespace text
  • @NotEmpty for strings, collections, arrays, or maps that must not be empty
  • @Size for string length or collection size
  • @Email for email format validation

5. Maven dependency

If you use Spring Boot, add:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

For Gradle:

implementation("org.springframework.boot:spring-boot-starter-validation")

6. Service-layer validation

You can also validate method parameters in Spring services:

import jakarta.validation.Valid;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Service
@Validated
public class UserService {

    public void createUser(@Valid UserForm userForm) {
        // business logic
    }
}

7. REST API validation example

For JSON request bodies:

import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserRestController {

    @PostMapping("/api/users")
    public String createUser(@Valid @RequestBody UserForm userForm) {
        return "User created";
    }
}

For REST APIs, invalid input usually results in a 400 Bad Request.

Summary

Use this pattern:

@PostMapping("/submit")
public String submit(@Valid MyForm form, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form-page";
    }

    return "redirect:/success";
}

That is the typical Spring MVC form validation flow.