Learn Spring Β· 5/15

Validating and Transforming Data

7 min read

🧱 Validating and Transforming Data in Spring

Welcome, fellow developer! Grab a cup of coffee β˜•, and let's talk about keeping our Spring applications robust and clean. In the world of software, the data we receive from the outside world can be a bit like a surprise box – you never know what you're gonna get. This guide will walk you through the essential practices of validating incoming data and transforming it to fit our application's needs.


1. The DTO Pattern: Decoupling Internal Models from Public APIs

The Problem: The Over-Exposed Model

Imagine you have a User entity that you use to store user data in your database. It probably looks something like this:

java
@Entity
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String username;
    private String password; // Uh oh...
    private String email;
    private LocalDateTime createdAt;
    // ...getters and setters
}

Now, what happens if you directly use this User entity in your public API? A client could potentially see the encrypted password hash, the creation date, and other internal details. Even worse, if a client sends a request to create a user, they could try to set the id or createdAt fields, which should be managed internally. This tight coupling between your internal data model and your public API is a recipe for security vulnerabilities and maintenance headaches.

The Solution: Data Transfer Objects (DTOs) 🎭

A Data Transfer Object (DTO) is a simple object used to transfer data between different layers of an application. Think of it as a carefully crafted message that contains only the necessary information for a specific task.

By using DTOs, we can decouple our internal domain models (entities) from what we expose to the outside world. This gives us several superpowers:

  • Enhanced Security: We only expose the data that is absolutely necessary, hiding sensitive information.
  • API Stability: We can change our internal entities without breaking the public API contract, as long as the DTO remains the same.
  • Flexibility: We can create different DTOs for different use cases (e.g., one for user creation, another for displaying user profiles).

Here's how we can create a UserDto for creating a new user:

java
public class UserCreateDto {
    private String username;
    private String password;
    private String email;
    // ...getters and setters
}

And another for displaying user information:

java
public class UserViewDto {
    private Long id;
    private String username;
    private String email;
    // ...getters and setters
}

Notice how UserCreateDto has a password field, but UserViewDto doesn't. This is the power of DTOs in action!


2. Object Mapping Basics: Converting Entities to DTOs (Manual vs MapStruct)

The Problem: The Tedious Transformation

Now that we have our DTOs, we need a way to convert our User entity to a UserViewDto and a UserCreateDto to a User entity. The most straightforward way is to do it manually.

Manual Mapping: The DIY Approach πŸ‘¨β€πŸ”§

Manual mapping involves writing the conversion logic yourself.

java
public class UserMapper {
    public UserViewDto toUserViewDto(User user) {
        UserViewDto dto = new UserViewDto();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        return dto;
    }

    public User toUser(UserCreateDto dto) {
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(dto.getPassword()); // Remember to hash this!
        user.setEmail(dto.getEmail());
        return user;
    }
}

While simple and offering full control, manual mapping can become incredibly tedious and error-prone as your objects get more complex and numerous. Imagine doing this for dozens of fields! 😱

MapStruct: The Code-Generating Superhero πŸ¦Έβ€β™€οΈ

Enter MapStruct, a compile-time code generator that automates the process of mapping between Java beans. It's fast, type-safe, and takes away the boilerplate.

Getting Started with MapStruct:

First, add the necessary dependencies to your pom.xml:

xml
<dependencies>
    <!-- ... other dependencies -->
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>1.5.5.Final</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>17</source>
                <target>17</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>1.5.5.Final</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

Now, we can define a mapper interface:

java
@Mapper(componentModel = "spring")
public interface UserMapper {
    UserViewDto toUserViewDto(User user);
    User toUser(UserCreateDto userCreateDto);
}

That's it! During compilation, MapStruct will generate a concrete implementation of this interface. Because we set componentModel = "spring", we can inject this mapper into our services and controllers just like any other Spring bean.

Interesting Fact: MapStruct works its magic during the compilation phase, so there's no runtime performance overhead from reflection, which some other mapping libraries use.


3. Defending Your API: Input Validation with @Valid, @NotNull, and @Size

The Problem: Trusting a Stranger's Input

Never trust data coming from the client! πŸ™…β€β™‚οΈ What if someone tries to create a user with a blank username or a password that's only two characters long? This could lead to inconsistent data and security issues.

The Solution: Declarative Validation with Annotations πŸ›‘οΈ

Spring Boot provides excellent support for validation using annotations from the Jakarta Bean Validation API. We can add these annotations directly to our DTO fields to declare the validation rules.

Let's beef up our UserCreateDto:

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

public class UserCreateDto {

    @NotBlank(message = "Username cannot be blank")
    private String username;

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

    @NotBlank(message = "Email cannot be blank")
    @Email(message = "Please provide a valid email address")
    private String email;

    // ...getters and setters
}

Here's what these annotations do:

  • @NotBlank: Ensures the field is not null and the trimmed length is greater than zero.
  • @Size(min = ...): Enforces a minimum length for a string.
  • @Email: Checks if the string is a valid email format.

Now, to trigger the validation, we use the @Valid annotation in our controller:

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

    // ... constructor injection for service

    @PostMapping
    public ResponseEntity<UserViewDto> createUser(@Valid @RequestBody UserCreateDto userCreateDto) {
        // If validation fails, a MethodArgumentNotValidException will be thrown
        // and our global exception handler will catch it (more on this next!)
        User newUser = userService.createUser(userCreateDto);
        return new ResponseEntity<>(userMapper.toUserViewDto(newUser), HttpStatus.CREATED);
    }
}

If the validation fails, Spring will throw a MethodArgumentNotValidException before our createUser method is even executed.


4. Handling Validation Exceptions: Returning Meaningful Error Messages

The Problem: The Ugly Default Error Response

When a validation exception occurs, by default, Spring Boot sends back a generic and often unhelpful error response. Your users will be left scratching their heads, wondering what they did wrong.

The Solution: The @ControllerAdvice and @ExceptionHandler Duo πŸ¦Έβ€β™‚οΈπŸ¦Έβ€β™€οΈ

We can create a global exception handler to catch specific exceptions and format a beautiful, informative error response.

Let's create a class annotated with @RestControllerAdvice:

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

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
                errors.put(error.getField(), error.getDefaultMessage()));
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

Here's the breakdown:

  • @RestControllerAdvice: This annotation allows us to consolidate our exception handling logic in one place that applies to all controllers.
  • @ExceptionHandler(MethodArgumentNotValidException.class): This tells Spring to call this method whenever a MethodArgumentNotValidException is thrown.

Now, when validation fails, the client will receive a response like this:

json
{
    "password": "Password must be at least 8 characters long",
    "username": "Username cannot be blank"
}

Much better, right? The client now knows exactly what to fix.

By following these steps, you can build Spring applications that are not only functional but also secure, maintainable, and user-friendly. Happy coding! πŸ’»

πŸ“š Further Reading

Challenge

Challenge: Implement a Robust Product Creation Endpoint

You are tasked with building a secure and robust REST API endpoint for creating products in a Spring Boot application. Your goal is to correctly implement the Data Transfer Object (DTO) pattern, apply input validation, use MapStruct for object mapping, and provide a custom, user-friendly error response for validation failures.

Complete the provided skeleton code to meet the following requirements:

  1. ProductCreateDto.java: This DTO will be used for incoming create requests. It must have the following fields and validation rules:

    • name: A String that cannot be blank.
    • sku: A String representing the Stock Keeping Unit. It cannot be blank and must be exactly 8 characters long.
    • price: A BigDecimal that must be a positive number.
  2. ProductViewDto.java: This DTO will be used for API responses. It should contain the following fields:

    • id: A Long.
    • name: A String.
    • price: A BigDecimal.
  3. ProductMapper.java: Define a MapStruct mapper interface that can:

    • Convert a ProductCreateDto to a Product entity.
    • Convert a Product entity to a ProductViewDto.
    • Ensure the mapper is configured to be a Spring component.
  4. GlobalExceptionHandler.java: Implement a global exception handler that specifically catches MethodArgumentNotValidException. When this exception occurs, the handler must:

    • Respond with an HTTP 400 Bad Request status.
    • Return a JSON body containing a map of field names to their validation error messages (e.g., {"sku": "must be exactly 8 characters long"}).
  5. ProductController.java: Complete the controller to handle product creation. The createProduct method must:

    • Be mapped to handle POST requests to /products.
    • Validate the incoming ProductCreateDto from the request body.
    • Use the ProductMapper to convert the DTO to a Product entity. For this exercise, you can create a new Product instance and set a dummy ID (e.g., 1L) before mapping back, as we are not using a real database.
    • Use the ProductMapper again to convert the resulting Product entity into a ProductViewDto.
    • Return the ProductViewDto in a ResponseEntity with an HTTP 201 Created status.

Expected result

Your final code should consist of five completed classes.

  1. ProductCreateDto.java should have three fields: name annotated with @NotBlank, sku annotated with @NotBlank and @Size(min=8, max=8), and price annotated with @Positive.

  2. ProductViewDto.java should have three fields: id, name, and price.

  3. ProductMapper.java should be an interface annotated with @Mapper(componentModel = "spring"). It must declare two abstract methods: Product toEntity(ProductCreateDto dto); and ProductViewDto toViewDto(Product product);.

  4. GlobalExceptionHandler.java should be annotated with @RestControllerAdvice. It must contain a method annotated with @ExceptionHandler(MethodArgumentNotValidException.class) and @ResponseStatus(HttpStatus.BAD_REQUEST). This method should accept a MethodArgumentNotValidException parameter and return a Map<String, String> containing the validation errors, where the key is the field name and the value is the error message.

  5. ProductController.java should have a createProduct method annotated with @PostMapping. The method's signature should accept a @Valid @RequestBody ProductCreateDto. Inside the method, you should use the injected productMapper to convert the incoming DTO to a Product entity, then convert that entity back to a ProductViewDto, and finally return it within a ResponseEntity with an HttpStatus.CREATED status.

java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.