Bird
Raised Fist0
Spring Bootframework~20 mins

Request validation preview in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Request Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Spring Boot controller receives invalid input with @Valid?

Consider a Spring Boot REST controller method annotated with @Valid on a request body. What is the default behavior when the input fails validation?

Spring Boot
public record UserRequest(@NotBlank String name, @Min(18) int age) {}

@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody UserRequest user) {
    return ResponseEntity.ok("User created");
}
ASpring Boot automatically returns a 400 Bad Request with a validation error message without entering the controller method.
BThe controller method runs and returns a 200 OK with "User created" regardless of validation errors.
CThe controller method throws a NullPointerException if validation fails.
DThe controller method returns a 500 Internal Server Error when validation fails.
Attempts:
2 left
💡 Hint

Think about how Spring Boot handles validation exceptions by default.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly applies validation annotations to a Spring Boot request DTO?

Choose the code snippet that correctly uses validation annotations on a Spring Boot record used as a request DTO.

Apublic record ProductRequest(@NotNull String name, @Size(min=1) int quantity) {}
Bpublic record ProductRequest(@NotBlank int name, @Min(1) String quantity) {}
Cpublic record ProductRequest(@Min(1) String name, @NotEmpty int quantity) {}
Dpublic record ProductRequest(@NotEmpty String name, @Positive int quantity) {}
Attempts:
2 left
💡 Hint

Remember which annotations apply to which data types.

🔧 Debug
advanced
2:00remaining
Why does this Spring Boot controller not return validation errors as expected?

Given the controller method below, why might validation errors not trigger a 400 response?

Spring Boot
public record OrderRequest(@NotNull String productId, @Min(1) int quantity) {}

@PostMapping("/orders")
public ResponseEntity<String> placeOrder(OrderRequest order) {
    return ResponseEntity.ok("Order placed");
}
AThe <code>@Min</code> annotation cannot be used on primitive int types.
BThe <code>OrderRequest</code> record must be a class, not a record, for validation to work.
CThe <code>@RequestBody</code> annotation is missing, so Spring does not bind the JSON to the object and skip validation.
DThe <code>@Valid</code> annotation is missing on the <code>OrderRequest</code> parameter, so validation is not triggered.
Attempts:
2 left
💡 Hint

Think about how Spring binds HTTP request data to method parameters.

❓ state_output
advanced
2:00remaining
What is the HTTP response status and body when validation fails in this Spring Boot controller?

Given the controller method below, what is the HTTP status code and response body when the client sends {"name":"", "age":15}?

Spring Boot
public record UserRequest(@NotBlank String name, @Min(18) int age) {}

@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody UserRequest user) {
    return ResponseEntity.ok("User created");
}
AStatus 400 Bad Request with a JSON body listing 'name' must not be blank and 'age' must be at least 18.
BStatus 200 OK with body 'User created'.
CStatus 500 Internal Server Error with empty body.
DStatus 422 Unprocessable Entity with plain text error message.
Attempts:
2 left
💡 Hint

Recall the default error response Spring Boot sends on validation failure.

🧠 Conceptual
expert
3:00remaining
How can you customize the validation error response in Spring Boot globally?

Which approach allows you to globally customize the JSON structure returned when validation errors occur in a Spring Boot REST API?

AAdd a custom message attribute to each validation annotation on the DTO fields.
BImplement a @ControllerAdvice class with an @ExceptionHandler for MethodArgumentNotValidException to build a custom response body.
COverride the toString() method of the request DTO to return custom error messages.
DUse @ResponseStatus on the controller method to change the HTTP status code.
Attempts:
2 left
💡 Hint

Think about how Spring Boot handles exceptions globally.

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

  1. 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.
  2. 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.
  3. Final Answer:

    To trigger validation of the incoming request data based on annotations in the DTO -> Option A
  4. 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

  1. Step 1: Recognize validation annotations

    Annotations like @NotNull are used on fields to define validation rules in DTO classes.
  2. Step 2: Identify incorrect annotations

    @Valid is used on method parameters, not fields; @RequestBody and @Autowired are unrelated to field validation.
  3. Final Answer:

    public class UserDTO { @NotNull private String name; } -> Option C
  4. 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

  1. Step 1: Understand @NotBlank validation

    The @NotBlank annotation requires the field to be non-null and contain at least one non-whitespace character.
  2. 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.
  3. Final Answer:

    The request will fail validation and return a 400 Bad Request with an error message -> Option D
  4. Quick Check:

    @NotBlank empty input causes 400 error [OK]
Hint: Empty strings fail @NotBlank, causing 400 errors [OK]
Common Mistakes:
  • Assuming empty strings pass validation
  • 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

  1. 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.
  2. 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.
  3. Final Answer:

    Missing @RequestBody annotation on the method parameter -> Option B
  4. 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

  1. Step 1: Validate username with @NotBlank

    Username must not be null or empty, so @NotBlank is correct.
  2. 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.
  3. Step 3: Validate email format with @Email

    @Email annotation checks for valid email format.
  4. Final Answer:

    public class UserDTO { @NotBlank private String username; @Min(18) private int age; @Email private String email; } -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard