0
0
Spring Bootframework~30 mins

Request validation preview in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Validation Preview in Spring Boot
📖 Scenario: You are building a simple Spring Boot web application that accepts user data through a form. To keep the data clean and safe, you want to check the user's input before saving it.
🎯 Goal: Create a Spring Boot controller that validates a user registration request using annotations. You will define a data class with validation rules, configure a controller to accept the data, and ensure validation errors are handled properly.
📋 What You'll Learn
Create a User class with fields name and email.
Add validation annotations to name and email fields.
Create a controller method to accept a POST request with a @Valid User object.
Add a BindingResult parameter to check for validation errors.
Return a simple success or error message based on validation.
💡 Why This Matters
🌍 Real World
Validating user input is essential in web applications to prevent bad data and security issues.
💼 Career
Understanding request validation is a key skill for backend developers working with Spring Boot.
Progress0 / 4 steps
1
Create User class with fields
Create a class called User with two private fields: String name and String email. Add public getters and setters for both fields.
Spring Boot
Need a hint?

Define private fields and generate public getter and setter methods for each.

2
Add validation annotations to User fields
Add the @NotBlank annotation to the name field and the @Email annotation to the email field in the User class. Also add @NotBlank to email to ensure it is not empty.
Spring Boot
Need a hint?

Use @NotBlank to ensure fields are not empty and @Email to check email format.

3
Create controller method to accept and validate User
Create a Spring Boot controller class called UserController. Inside it, write a method registerUser that handles POST requests at /register. The method should accept a @Valid User user parameter and a BindingResult bindingResult parameter. The method should return a String.
Spring Boot
Need a hint?

Create a controller with a POST method that accepts a validated User and BindingResult.

4
Add validation check and return response
Inside the registerUser method, check if bindingResult.hasErrors() is true. If yes, return the string "Error: Invalid data". Otherwise, return "Success: User registered".
Spring Boot
Need a hint?

Use bindingResult.hasErrors() to check validation and return messages accordingly.