Sub topic 7
Validating path variables and query parameters
This chapter assumes you have read the earlier chapters of this tutorial. It also assumes you can write a Spring MVC controller and that spring-boot-starter-validation is on your classpath. Request bodies are validated with @Valid on a DTO. Path variables and query parameters are single values with no DTO around them, so they need a different trigger and produce a different exception.
Why parameters need separate treatment
A request body is converted into an object, and @Valid asks Spring to validate that object. A path variable such as /orders/{id} or a query parameter such as ?page=2 is a plain long, int or String method argument. You put constraint annotations directly on the argument:
@GetMapping("/orders/{id}")
public String find(@PathVariable @Min(1) long id) { ... }Spring MVC does not act on these annotations unless validation is switched on for the controller. Without it, @Min(1) is silently ignored and /orders/-5 reaches your method. This is a common bug because the code looks protected.
Switching on parameter validation
Put @Validated on the controller class. This is Spring's own annotation, not the Jakarta one. It makes Spring wrap the controller in a proxy that validates arguments before each method call.
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.List;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/{id}")
public String find(@PathVariable @Min(1) long id) {
return "order " + id;
}
@GetMapping
public List<String> search(
@RequestParam @NotBlank @Size(max = 50) String status,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return List.of("status=" + status, "page=" + page, "size=" + size);
}
}Three details matter here.
- The constraint goes on the parameter, next to
@PathVariableor@RequestParam. Annotation order does not matter. - Defaults are applied before validation. If
sizeis missing, Spring binds20, and@Max(100)passes. - Primitive types such as
intcan never benull. For an optional parameter without a default, use a wrapper type such asInteger. Most constraints treatnullas valid, so add@NotNullonly if you need it. Required parameters are already enforced by@RequestParamitself.
Three failures, three exception types
A bad parameter can fail at three different stages. Each stage raises a different exception, and your error handling must cover all of them.
| Stage | Example request | Exception | Default result |
|---|---|---|---|
| Presence | `GET /orders` with no `status` | `MissingServletRequestParameterException` | 400 |
| Type conversion | `GET /orders/abc` | `MethodArgumentTypeMismatchException` | 400 |
| Constraint check | `GET /orders/0` | `ConstraintViolationException` | 500 |
The first two come from Spring MVC and already map to 400. The third comes from Bean Validation through the proxy. Spring does not map it to a status code, so an unhandled violation becomes a 500 Internal Server Error. This is a client mistake, so it should be a 400.
Handling ConstraintViolationException
Add a handler to the @RestControllerAdvice from the earlier chapter. It turns each violation into an entry in a ProblemDetail, in the same shape as the body-validation response, so clients parse one format.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Path;
import java.util.Map;
import java.util.TreeMap;
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 ParameterErrorHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleViolations(ConstraintViolationException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new TreeMap<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.putIfAbsent(lastNode(violation.getPropertyPath()), violation.getMessage());
}
problem.setProperty("errors", errors);
return problem;
}
private static String lastNode(Path path) {
String name = "";
for (Path.Node node : path) {
name = node.getName();
}
return name;
}
}The property path of a method parameter looks like search.page, which is the method name followed by the parameter name. The helper keeps only the last part, so the client sees page. A request to GET /orders?status=&page=-1 returns:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/orders",
"errors": {
"page": "must be greater than or equal to 0",
"status": "must not be blank"
}
}The TreeMap sorts the keys. A ConstraintViolationException holds a Set, which has no stable order, so sorting keeps responses and tests predictable.
What changed in Spring Framework 6.1
Spring Framework 6.1 (Spring Boot 3.2 and later) added built-in method validation for controllers. If you leave @Validated off the class and put constraints on handler parameters, Spring MVC validates them itself. A failure then raises HandlerMethodValidationException, which Spring maps to 400 by default.
The two approaches differ in the exception you handle:
| Setup | Mechanism | Exception on failure |
|---|---|---|
| `@Validated` on the class | AOP proxy | `ConstraintViolationException` |
| No class-level `@Validated`, Spring 6.1+ | Built-in MVC validation | `HandlerMethodValidationException` |
Do not mix them without knowing which one applies. If you put @Validated on the class, the proxy runs first and you get ConstraintViolationException. If you drop it, you must handle HandlerMethodValidationException instead, or your handler never fires. This tutorial uses class-level @Validated, which works on every Spring Boot 3.x version. It also matches the same annotation used for validating service classes later in the tutorial.
Validating several query parameters as one object
When a search endpoint has many filters, a long parameter list is hard to read. You can bind query parameters to a record and validate the record. Omit @RequestBody and use @Valid alone:
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
record OrderFilter(
@Size(max = 50) String status,
@Min(0) Integer page,
@Min(1) @Max(100) Integer size) {
}
@RestController
class OrderSearchController {
@GetMapping("/orders/search")
public String search(@Valid OrderFilter filter) {
return "status=" + filter.status();
}
}This behaves like body validation, not like parameter validation. Spring binds the query string into the record by name, then validates it. A failure raises a BindException (or its subclass MethodArgumentNotValidException, depending on the Spring version), not ConstraintViolationException. Your handler for invalid bodies can usually cover this case too. The class does not need @Validated.
Records bound this way must use wrapper types for optional values. A missing page becomes null for Integer, but a primitive int would be set to 0 and hide the omission. Record components also have no defaultValue, so apply defaults in code after validation.
Common mistakes
- Forgetting
@Validated. The constraints are ignored, and no error appears anywhere. Test one bad value for every endpoint you annotate. - Putting the constraint on the wrong thing.
@Min(1)must sit on the parameter, not on the method. - Expecting a 400 without a handler. Constraint violations become 500 until you handle
ConstraintViolationException. - Validating non-existence as format.
@Min(1)checks that an ID has a valid shape. It does not check that order9999exists. Missing resources are a 404, decided in the service layer. - Using
@NotNullon a path variable. A path variable is nevernull, because an empty segment does not match the route. The constraint does nothing. - Constraining strings with
@Sizebut not@NotBlank.@Size(max = 50)accepts an empty string. Combine it with@NotBlankwhen empty values are invalid. - Exposing raw messages. Default messages such as
must be greater than or equal to 0are fine for developers. The messages chapter covers how to customize them.
Testing parameter validation
A MockMvc test in a @WebMvcTest slice checks that each stage returns 400 and that the body has the expected shape. Add your @RestControllerAdvice to the slice by listing it in the @WebMvcTest annotation.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(OrderController.class)
@Import(ParameterErrorHandler.class)
class OrderControllerTest {
@Autowired
MockMvc mockMvc;
@Test
void zeroIdIsRejected() throws Exception {
mockMvc.perform(get("/orders/0"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.find").exists());
}
@Test
void nonNumericIdIsRejected() throws Exception {
mockMvc.perform(get("/orders/abc"))
.andExpect(status().isBadRequest());
}
@Test
void oversizedPageSizeIsRejected() throws Exception {
mockMvc.perform(get("/orders").param("status", "OPEN").param("size", "500"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.size").exists());
}
}The first test asserts the key find. For a path variable, the last path node is the argument name, which is id, so check the output of your build. If your parameter name is id, the key is id. Adjust the assertion to match your handler's output before relying on it.
Decision criteria
- Use constraints on parameters when you have one to three simple values.
- Bind to a validated record when you have many related filters, or when the same filter is reused in several endpoints.
- Keep format checks (range, length, pattern) at the boundary, and keep existence and permission checks in services.
- Choose between class-level
@Validatedand built-in 6.1 validation once per project, and write your handlers for that choice.
Exercise
A controller method is declared as find(@PathVariable @Min(1) long id) in a class annotated only with @RestController, on Spring Boot 3.1. A client calls GET /orders/-5. What happens, and what two changes make the API return a 400 with an errors map?
Show answer
The request succeeds and find runs with id = -5, because no @Validated is present on Spring Boot 3.1, so nothing checks @Min(1). First, add @Validated to the controller class so the proxy validates arguments. Second, add an @ExceptionHandler(ConstraintViolationException.class) in a @RestControllerAdvice that returns a 400 ProblemDetail with an errors property. Without the handler, the violation becomes a 500.
Exercise
A request is GET /orders/abc where id is a long with @Min(1), in a class with @Validated. Which exception is raised, and does the constraint ever run?
Show answer
MethodArgumentTypeMismatchException is raised during type conversion. The constraint never runs, because the value cannot be converted to a long. Spring maps this exception to 400 by default.