0
0
Spring Bootframework~30 mins

@Valid annotation on request body in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Valid Annotation on Request Body in Spring Boot
📖 Scenario: You are building a simple Spring Boot REST API to register users. You want to make sure the user data sent in the request body is valid before processing it.
🎯 Goal: Learn how to use the @Valid annotation on a request body to automatically validate incoming data in a Spring Boot controller.
📋 What You'll Learn
Create a User class with validation annotations
Create a controller method that accepts a User object in the request body
Use the @Valid annotation on the request body parameter
Add a configuration to handle validation errors gracefully
💡 Why This Matters
🌍 Real World
Validating user input in REST APIs is essential to prevent bad data from entering your system and to provide clear feedback to API clients.
💼 Career
Backend developers often need to validate incoming data in web applications. Knowing how to use @Valid in Spring Boot is a common and important skill.
Progress0 / 4 steps
1
Create User class with validation annotations
Create a class called User with two fields: String name and String email. Add @NotBlank annotation on name and @Email annotation on email. Import the annotations from jakarta.validation.constraints.
Spring Boot
Need a hint?

Use @NotBlank on the name field and @Email on the email field inside the User class.

2
Create controller with POST method accepting User
Create a Spring REST controller class called UserController. Add a method registerUser that handles POST requests at /users. The method should accept a @RequestBody User user parameter and return String.
Spring Boot
Need a hint?

Use @RestController on the class and @PostMapping("/users") on the method. The method should accept @RequestBody User user.

3
Add @Valid annotation to request body parameter
Modify the registerUser method to add the @Valid annotation before the @RequestBody User user parameter to enable validation.
Spring Boot
Need a hint?

Put @Valid right before @RequestBody User user in the method parameter.

4
Add exception handler for validation errors
Add a method in UserController annotated with @ExceptionHandler(MethodArgumentNotValidException.class) that returns a String message "Validation failed" when validation errors occur.
Spring Boot
Need a hint?

Create a method annotated with @ExceptionHandler(MethodArgumentNotValidException.class) that returns the string "Validation failed".