Sub topic 9
Validating path variables and query parameters
This chapter assumes you can already bind @PathVariable and @RequestParam values and that you have seen Bean Validation on a request body with @Valid. It also assumes a Spring Boot 3.x project, Spring Framework 6.1 or later. The getParameterValidationResults() call used below needs Spring Framework 6.2 (Spring Boot 3.4) or later.
Why type conversion is not enough
Type conversion rejects values that have the wrong shape. /api/books/abc fails because abc is not a Long. It accepts any value that does parse, including ones that make no sense for your domain:
/api/books/-5converts to theLong-5.?page=-3converts to theint-3.?size=1000000converts to anintthat would ask the database for a million rows.?author=converts to an empty string.
Bean Validation constraints close this gap. You write the rule next to the parameter, and Spring checks it before your method body runs.
Add the validation starter
Since Spring Boot 2.3, spring-boot-starter-web no longer includes a Bean Validation implementation. Without one, constraint annotations on parameters are silently ignored. Add the starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>For Gradle, the equivalent is implementation 'org.springframework.boot:spring-boot-starter-validation'. The starter brings in Hibernate Validator, the reference implementation of the Jakarta Bean Validation API.
Put constraints on the parameters
Place constraint annotations directly on the handler parameters. You do not need @Valid for this, because @Valid is for cascading into an object's fields.
package com.example.books;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@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 = 100) String author,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return service.search(author, page, size);
}
}Book and BookService are the types from the earlier chapters.
Some common constraints for parameters:
| Annotation | Checks | Typical use |
|---|---|---|
| `@Positive`, `@PositiveOrZero` | Number is greater than 0, or at least 0 | IDs, counts |
| `@Min`, `@Max` | Number lies within bounds | `page`, `size` |
| `@Size` | String length, or collection or array size | Search terms |
| `@NotBlank` | String has at least one non-whitespace character | Required text |
| `@Pattern` | String matches a regular expression | Codes such as ISBNs |
| `@Past`, `@Future` | Date lies before or after now | Date filters |
How the validation runs
Spring Framework 6.1 added built-in method validation for controllers. When a handler method has constraint annotations on its parameters, Spring validates the arguments after it resolves them and before it invokes the method. If any constraint fails, it throws HandlerMethodValidationException, which maps to a 400 response.
A request such as GET /api/books/-5 now returns 400 instead of reaching the service. Your service.get(id) code can assume the ID is positive.
Controller-level `@Validated` on older versions
On Spring Framework 6.0 and earlier (Spring Boot 3.0), the built-in mechanism does not exist. There you must annotate the controller class with @Validated, and failures surface as ConstraintViolationException. If you maintain such a project, or you validate parameters of a @Service bean, handle that exception too:
@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;
}The property path has the form methodName.parameterName, for example getById.id. Parameter names appear only if the code was compiled with the -parameters flag. The Spring Boot Maven and Gradle plugins configure that flag for you. Otherwise you get arg0.
Return a consistent 400 body
By default, a failed constraint produces a 400 with little detail. To match the ProblemDetail format used for body errors, add a handler for HandlerMethodValidationException to the ApiExceptionHandler class from the previous chapters:
@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 -> {
String name = result.getMethodParameter().getParameterName();
String messages = result.getResolvableErrors().stream()
.map(MessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining("; "));
errors.put(name, messages);
});
problem.setProperty("errors", errors);
return problem;
}The handler needs these imports in addition to those already in the class: org.springframework.context.MessageSourceResolvable, org.springframework.web.method.annotation.HandlerMethodValidationException, and java.util.stream.Collectors.
Each ParameterValidationResult describes one parameter and holds one error per failed constraint. A parameter with @Min(1) @Max(100) can fail only one of them at a time, but a @Size and a @Pattern on the same parameter can both fail, which is why the messages are joined.
A request to GET /api/books?page=-1&size=500 now returns a body like this:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request parameters failed validation",
"instance": "/api/books",
"errors": {
"page": "must be greater than or equal to 0",
"size": "must be less than or equal to 100"
}
}The messages come from Hibernate Validator's default message bundle. Set the message attribute on a constraint to override one, for example @Min(value = 1, message = "size must be at least 1").
Edge cases and gotchas
Missing versus invalid. A missing required parameter is not a constraint failure. Spring raises MissingServletRequestParameterException (400) before validation runs. Constraints apply only to values that are present.
Null passes most constraints. @Min, @Max, @Size, @Pattern, and @Positive all treat null as valid. This is deliberate, so that optional parameters can carry constraints. For author above, an absent parameter passes @Size. If a value must be present, combine the constraint with required = true (the default) or add @NotNull.
Empty strings are not null. ?author= binds to "", not null. @Size(min = 2) rejects it. @NotBlank also rejects it, but @Pattern and @Size(max = ...) accept it. Decide whether an empty value should mean "absent" and validate accordingly.
Defaults are validated. A defaultValue is applied before validation. A default that violates its own constraint produces a 400 for requests that omit the parameter, so keep defaults inside the allowed range.
Primitive types cannot be null. @RequestParam(required = false) int page fails with a conversion error when the parameter is missing, because there is no null to assign to an int. Use Integer, or give the parameter a defaultValue.
Constraints on collection elements. To validate each value of a multi-valued parameter, put the constraint on the type argument:
@GetMapping("/by-ids")
public List<Book> getMany(@RequestParam List<@Positive Long> ids) {
return service.getAll(ids);
}A request such as ?ids=1,2,-3 then fails on the third element. Spring splits the comma-separated value into a list during conversion.
Enums and dates. Constraints do not replace conversion. For an enum parameter, an unknown value fails conversion with a type mismatch (400). A @Past constraint on a LocalDate parameter runs only after @DateTimeFormat has parsed the string successfully.
Two exception types for one endpoint. A method with a @Valid @RequestBody and constrained query parameters can fail in more than one way: MethodArgumentNotValidException for body errors, HandlerMethodValidationException for parameter errors. Register a handler for each.
Check the behavior with curl
curl -i http://localhost:8080/api/books/-5
curl -i "http://localhost:8080/api/books?page=-1&size=500"
curl -i "http://localhost:8080/api/books?author=x"All three return 400 Bad Request. The second returns two entries under errors, and the third reports that author must have a length between 2 and 100.
Exercise
A controller method declares @RequestParam(required = false) @Size(min = 3) String author. A client sends GET /api/books with no author parameter, and a second client sends GET /api/books?author=ab. What status does each request get, and why? Which exception does the second request raise on Spring Framework 6.1 or later?
Show answer
The first request passes validation. The parameter is absent, so it is null, and @Size treats null as valid. The method runs with author set to null and returns 200. The second request gets 400, because "ab" has length 2 and the constraint requires at least 3. The exception is HandlerMethodValidationException, thrown by Spring's built-in method validation before the controller method runs.
Exercise
You add @Validated to your controller class on Spring Boot 3.4 and a client sends GET /api/books/-5 to a method with @PathVariable @Positive Long id. Your ApiExceptionHandler only handles HandlerMethodValidationException. What does the client see, and how do you fix it?
Show answer
The client gets a 500 response. The class-level @Validated creates a proxy that throws jakarta.validation.ConstraintViolationException, and the handler does not cover it. Either remove the class-level @Validated so Spring's built-in method validation is used and throws HandlerMethodValidationException, or add an @ExceptionHandler(ConstraintViolationException.class) method that returns a 400 ProblemDetail.