Sub topic 9
Validating path variables and query parameters
This chapter assumes you have read the earlier chapters on @PathVariable, @RequestParam, and @Valid on request bodies. It also assumes Spring Boot 3.2 or later, which includes Spring Framework 6.1.
Type conversion only checks that abc is not a Long. It does not reject -5 as an id or size=100000 as a page size. Constraint annotations on the method parameters can reject those values.
Add the validation starter
Bean Validation needs an implementation on the classpath. In Spring Boot, add the starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Put constraints on the parameters
You place the constraint annotations directly next to @PathVariable and @RequestParam. A @Valid annotation is not needed here, because there is no object to cascade into.
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public Book getById(@PathVariable @Positive Long id) {
return service.get(id);
}
@GetMapping
public List<Book> search(
@RequestParam(required = false) @Size(min = 2, max = 50) String author,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return service.search(author, page, size);
}
}Three details matter here:
- A
nullvalue passes@Size. Whenauthoris absent, no constraint fails. Add@NotBlankif the value is required, or userequired = true. - Defaults are applied before validation, so a default must satisfy its own constraints.
- Conversion runs first.
?size=abcfails with a type mismatch before any constraint is checked.
Two ways the validation runs
Spring has two mechanisms for method parameter validation, and they throw different exceptions.
- Built-in validation (Spring 6.1 and later). If a handler method has constraint annotations and the class is not annotated with
@Validated, Spring MVC validates the arguments itself. It throwsHandlerMethodValidationException, which Spring maps to 400. @Validatedon the class. Spring wraps the controller in a proxy, and the proxy throwsConstraintViolationException. Nothing maps it to a status, so the client gets a 500.
Return a 400 with details
Add a handler to the @RestControllerAdvice class from the previous chapter. Spring's own handling of HandlerMethodValidationException gives a bare 400. This version lists each failing parameter:
import org.springframework.web.method.annotation.HandlerMethodValidationException;
@ExceptionHandler(HandlerMethodValidationException.class)
public ProblemDetail handleParameterValidation(HandlerMethodValidationException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request parameters failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getParameterValidationResults().forEach(result ->
result.getResolvableErrors().forEach(error ->
errors.putIfAbsent(result.getMethodParameter().getParameterName(),
error.getDefaultMessage())));
problem.setProperty("errors", errors);
return problem;
}Parameter names are available when the code is compiled with -parameters. The Spring Boot Maven and Gradle plugins enable this by default.
If you do use @Validated, handle the other exception instead:
import jakarta.validation.ConstraintViolationException;
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleConstraintViolation(ConstraintViolationException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request parameters failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getConstraintViolations().forEach(v ->
errors.putIfAbsent(v.getPropertyPath().toString(), v.getMessage()));
problem.setProperty("errors", errors);
return problem;
}With this handler, the property path looks like getById.id, which includes the method name.
Try it
curl -i http://localhost:8080/api/books/-5
curl -i "http://localhost:8080/api/books?size=500"Both calls should return 400 with a ProblemDetail JSON body.
Exercise
A controller class has no @Validated annotation. A method declares @RequestParam @Min(1) int size, and a client calls ?size=0. Which exception is thrown, and what status does the client get if you add no handler for it?
Show answer
Spring 6.1's built-in method validation throws HandlerMethodValidationException, and Spring maps it to 400 Bad Request. If you add @Validated to the class, the exception becomes ConstraintViolationException and the client gets 500 unless you handle it.