Sub topic 7
Validating path variables and query parameters
This chapter assumes you can write a Spring MVC controller, have the spring-boot-starter-validation dependency on the classpath, and know how @Valid works on a request body. Here you will apply constraints to path variables and query parameters, and handle the exception this produces.
Why parameters need a different trigger
With a request body, @Valid on the parameter makes Spring validate the DTO. A path variable or a query parameter is usually a plain long or String. There is no object to cascade into, so the constraint sits directly on the method parameter.
Spring does not check these constraints by default. You enable them by putting @Validated on the controller class. Spring then wraps the controller in a proxy that validates method arguments before the method body runs.
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
public class OrderController {
@GetMapping("/orders/{id}")
public String find(@PathVariable @Min(1) long id) {
return "order " + id;
}
@GetMapping("/orders")
public String search(
@RequestParam @NotBlank @Size(max = 30) String customer,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return "orders for " + customer + ", page size " + size;
}
}A request to /orders/0 now fails because 0 is below the minimum of 1. A request to /orders?customer=acme&size=500 fails because 500 is above 100.
Two exceptions, two handlers
Which exception you get depends on where the constraint was declared.
| Where the constraint is | Exception thrown |
|---|---|
| Fields of a `@Valid @RequestBody` DTO | `MethodArgumentNotValidException` |
| Path variables and request parameters with `@Validated` | `ConstraintViolationException` |
Your existing handler for MethodArgumentNotValidException does not catch the second one. Without a handler, the client receives a 500 response, which wrongly suggests a server fault. Add a handler that returns 400.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ParameterExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleConstraintViolation(ConstraintViolationException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.putIfAbsent(violation.getPropertyPath().toString(), violation.getMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}The property path of a violation looks like find.id or search.size. It is the method name followed by the parameter name. The parameter name is only available if you compile with the -parameters flag, which the Spring Boot Maven and Gradle plugins set for you. Otherwise you see arg0.
Common errors
- Constraints are ignored. The class is missing
@Validated. This is the most frequent cause, and it fails silently. - Missing parameter gives a different error. If a required
@RequestParamis absent, Spring raisesMissingServletRequestParameterExceptionbefore your constraints run. Constraints such as@NotBlankonly apply once a value, possibly empty, is present. - Type mismatch.
/orders/abcfor alongid fails during type conversion withMethodArgumentTypeMismatchException, not a constraint violation. Handle it separately if you want a consistent 400 body. - Boxed types and null. Most constraints treat
nullas valid. Use@NotNullon anIntegerparameter if absence must fail.
Exercise
A controller method declares @PathVariable @Min(1) long id, but a request to /orders/-5 returns 200. What is the most likely cause, and how do you fix it?
Show answer
The controller class lacks @Validated, so the constraint on the parameter is never checked. Add @Validated to the class. Also add a handler for ConstraintViolationException so that failures return 400 instead of 500.
Exercise
Why does /orders?size=500 produce a ConstraintViolationException while an invalid field in a @Valid @RequestBody DTO produces MethodArgumentNotValidException?
Show answer
Body validation is run by Spring's argument resolver on the bound DTO and reports through a BindingResult. Parameter validation runs through a method-validation proxy enabled by @Validated, which throws the Bean Validation exception directly.