Performance: Request validation preview
This affects the server response time and user experience by validating input before processing the request.
@PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { // processing assumes valid input return ResponseEntity.ok("User created"); } // User class with validation annotations public class User { @NotBlank(message = "Name is required") private String name; // getters and setters }
public ResponseEntity<String> createUser(@RequestBody User user) {
if(user.getName() == null || user.getName().isEmpty()) {
return ResponseEntity.badRequest().body("Name is required");
}
// further processing
return ResponseEntity.ok("User created");
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation in controller | N/A | N/A | N/A | [X] Bad |
| Declarative validation with @Valid | N/A | N/A | N/A | [OK] Good |
@Valid annotation in Spring Boot request handling?@Valid@Valid annotation tells Spring Boot to check the incoming data against validation rules defined in the DTO class.@Valid does not do@Valid triggers validation [OK]@NotNull are used on fields to define validation rules in DTO classes.@Valid is used on method parameters, not fields; @RequestBody and @Autowired are unrelated to field validation.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");
}@NotBlank annotation requires the field to be non-null and contain at least one non-whitespace character.@NotBlank validation, so Spring Boot will reject the request and return a 400 error with validation details.UserDTO has validation annotations.username (not blank), age (minimum 18), and email (valid email format). Which combination of annotations in the DTO class is correct?Pass the test and this pattern moves unknown