java / beginner
Snippet
Validating REST Request Payloads with Jakarta Annotations
Spring Boot integrates with Jakarta Bean Validation to ensure incoming HTTP request data matches defined rules before controller logic executes. Adding annotations like @NotBlank and @Min to DTO fields enforces presence and range checks. Applying @Valid before @RequestBody triggers automatic validation, rejecting malformed input with HTTP 400 Bad Request.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class UserRegistrationDto {@NotBlank(message = "Username cannot be blank")private String username;@Min(value = 18, message = "Age must be at least 18")private int age;public String getUsername() { return username; }public void setUsername(String username) { this.username = username; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }}@RestController@RequestMapping("/api/users")public class UserController {@PostMappingpublic ResponseEntity<String> registerUser(@Valid @RequestBody UserRegistrationDto dto) {return ResponseEntity.ok("Registration valid for: " + dto.getUsername());}}
spring
Breakdown
1
@NotBlank(message = "Username cannot be blank")
Ensures that the string property is not null and contains at least one non-whitespace character.
2
@Min(value = 18, message = "Age must be at least 18")
Restricts the numeric integer property so that submitted values lower than 18 trigger a validation failure.
3
public ResponseEntity<String> registerUser(@Valid @RequestBody UserRegistrationDto dto)
The @Valid annotation instructs Spring to validate the incoming JSON body mapped to UserRegistrationDto prior to entering the method.