📖 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
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
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
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
Hint
Use bindingResult.hasErrors() to check validation and return messages accordingly.
Practice
(1/5)
1. What is the main purpose of using @Valid annotation in Spring Boot request handling?
easy
A. To trigger validation of the incoming request data based on annotations in the DTO
B. To automatically log the request data for debugging
C. To convert the request body into a JSON string
D. To disable validation for the request parameters
Solution
Step 1: Understand the role of @Valid
The @Valid annotation tells Spring Boot to check the incoming data against validation rules defined in the DTO class.
Step 2: Identify what @Valid does not do
It does not log data, convert to JSON, or disable validation. Its sole purpose is to trigger validation.
Final Answer:
To trigger validation of the incoming request data based on annotations in the DTO -> Option A
Quick Check:
@Valid triggers validation [OK]
Hint: Remember: @Valid means 'check this data' [OK]
Common Mistakes:
Thinking @Valid logs or converts data
Confusing @Valid with JSON serialization
Assuming @Valid disables validation
2. Which of the following is the correct way to apply validation annotations in a Spring Boot DTO class?
easy
A. public class UserDTO {
@Valid
private String name;
}
B. public class UserDTO {
@RequestBody
private String name;
}
C. public class UserDTO {
@NotNull
private String name;
}
D. public class UserDTO {
@Autowired
private String name;
}
Solution
Step 1: Recognize validation annotations
Annotations like @NotNull are used on fields to define validation rules in DTO classes.
Step 2: Identify incorrect annotations
@Valid is used on method parameters, not fields; @RequestBody and @Autowired are unrelated to field validation.
Final Answer:
public class UserDTO {
@NotNull
private String name;
} -> Option C
Quick Check:
Use validation annotations like @NotNull on fields [OK]
Hint: Validation annotations go on fields, not on parameters [OK]
Common Mistakes:
Using @Valid on fields instead of method parameters
Confusing @RequestBody with validation
Applying @Autowired to DTO fields
3. Given the following DTO and controller method, what will happen if the client sends a request with an empty email field?
public class UserDTO {
@NotBlank
private String email;
// getters and setters
}
@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody UserDTO user) {
return ResponseEntity.ok("User created");
}
medium
A. The request will be ignored silently
B. The request will succeed and return "User created"
C. The server will throw a NullPointerException
D. The request will fail validation and return a 400 Bad Request with an error message
Solution
Step 1: Understand @NotBlank validation
The @NotBlank annotation requires the field to be non-null and contain at least one non-whitespace character.
Step 2: Analyze the empty email input
An empty string fails @NotBlank validation, so Spring Boot will reject the request and return a 400 error with validation details.
Final Answer:
The request will fail validation and return a 400 Bad Request with an error message -> Option D
Expecting NullPointerException instead of validation error
Thinking server ignores invalid input
4. Identify the error in this Spring Boot controller method that uses request validation:
@PostMapping("/register")
public ResponseEntity<String> registerUser(@Valid UserDTO user) {
// method body
}
Assuming UserDTO has validation annotations.
medium
A. Missing @Valid annotation on the method parameter
B. Missing @RequestBody annotation on the method parameter
C. Method should return void instead of ResponseEntity
D. UserDTO should not have validation annotations
Solution
Step 1: Check parameter annotations for validation
To validate request body data, the parameter must be annotated with @RequestBody so Spring can deserialize JSON into the DTO.
Step 2: Confirm @Valid usage
While @Valid triggers validation, without @RequestBody the data won't be bound from the request body, so validation won't run.
Final Answer:
Missing @RequestBody annotation on the method parameter -> Option B
Quick Check:
Use @RequestBody to bind JSON, then @Valid to validate [OK]
Hint: Always use @RequestBody with @Valid for JSON validation [OK]
Common Mistakes:
Forgetting @RequestBody causes no data binding
Assuming @Valid alone binds data
Thinking return type affects validation
5. You want to validate a user registration request with fields username (not blank), age (minimum 18), and email (valid email format). Which combination of annotations in the DTO class is correct?
hard
A. public class UserDTO {
@NotBlank
private String username;
@Min(18)
private int age;
@Email
private String email;
}
B. public class UserDTO {
@NotNull
private String username;
@Max(18)
private int age;
@Pattern(regexp = ".*@.*")
private String email;
}
C. public class UserDTO {
@NotBlank
private String username;
@Min(18)
private String age;
@Email
private String email;
}
D. public class UserDTO {
@NotEmpty
private String username;
@Min(18)
private Integer age;
@Email
private String email;
}
Solution
Step 1: Validate username with @NotBlank
Username must not be null or empty, so @NotBlank is correct.
Step 2: Validate age with @Min(18) and correct type
Age must be at least 18 and an integer type; int with @Min(18) fits.
Step 3: Validate email format with @Email
@Email annotation checks for valid email format.
Final Answer:
public class UserDTO {
@NotBlank
private String username;
@Min(18)
private int age;
@Email
private String email;
} -> Option A
Quick Check:
Use @NotBlank, @Min(18), and @Email for these fields [OK]
Hint: Match annotation to field type and validation need [OK]
Common Mistakes:
Using @Max instead of @Min for age
Using String type for age with @Min
Using @NotNull instead of @NotBlank for username
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.