0
0
Spring Bootframework~30 mins

DTO validation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
DTO Validation in Spring Boot
📖 Scenario: You are building a simple Spring Boot web application that accepts user registration data. To keep the data clean and safe, you need to validate the input before processing it.
🎯 Goal: Create a Data Transfer Object (DTO) for user registration with validation annotations. Then configure a controller to accept and validate this DTO.
📋 What You'll Learn
Create a UserRegistrationDTO class with fields: username, email, and age
Add validation annotations to ensure username is not empty, email is a valid email, and age is at least 18
Create a controller method that accepts UserRegistrationDTO as a request body
Enable validation so that invalid data returns an error response
💡 Why This Matters
🌍 Real World
Validating user input in web applications is essential to prevent bad data and security issues.
💼 Career
Understanding DTO validation is important for backend developers working with Spring Boot to build robust APIs.
Progress0 / 4 steps
1
Create UserRegistrationDTO with fields
Create a class called UserRegistrationDTO with three private fields: String username, String email, and int age. Add public getters and setters for each field.
Spring Boot
Need a hint?

Define the class and fields exactly as named. Use standard getter and setter methods.

2
Add validation annotations to UserRegistrationDTO
Add validation annotations to the UserRegistrationDTO fields: annotate username with @NotEmpty, email with @Email, and age with @Min(18). Import the annotations from jakarta.validation.constraints.
Spring Boot
Need a hint?

Use the correct validation annotations on the fields. Make sure to import them.

3
Create controller method to accept UserRegistrationDTO
Create a Spring Boot controller class called UserController. Inside it, create a method registerUser annotated with @PostMapping("/register") that accepts a @RequestBody UserRegistrationDTO user parameter. Add @Valid before @RequestBody to enable validation.
Spring Boot
Need a hint?

Use @RestController on the class and @PostMapping on the method. Remember to add @Valid before @RequestBody.

4
Enable validation error handling
Add @Valid to the UserRegistrationDTO parameter in the registerUser method to trigger validation. Also, add @ResponseStatus(HttpStatus.BAD_REQUEST) and @ExceptionHandler(MethodArgumentNotValidException.class) in the controller to handle validation errors and return a simple error message.
Spring Boot
Need a hint?

Add an exception handler method in the controller to catch validation errors and respond with a 400 status and message.