Sobes.tech
Junior — Middle

How can you configure input data validation for incoming HTTP requests when using Spring?

sobes.tech AI

Answer from AI

In Spring, data validation for incoming HTTP requests is usually performed using validation annotations from the javax.validation package (such as @NotNull, @Size, @Email, etc.) together with the @Valid or @Validated annotation in the controller.

Example:

@RestController
public class UserController {

    @PostMapping("/users")
    public ResponseEntity<String> createUser(@Valid @RequestBody UserDto userDto) {
        // if the data is invalid, Spring will automatically return a 400 error
        return ResponseEntity.ok("User created");
    }
}

public class UserDto {
    @NotNull
    @Size(min = 2, max = 30)
    private String name;

    @Email
    private String email;

    // getters and setters
}

If the data fails validation, Spring will throw a MethodArgumentNotValidException, which can be handled globally via @ControllerAdvice for custom responses.