Sub topic 10
Binding Several Query Parameters to One Object
This chapter assumes you can write a Spring Boot controller with @GetMapping and @RequestParam, you know Java records, and you have seen Bean Validation annotations such as @Min on a request body. It uses Spring Framework 6.x (Spring Boot 3.x).
The problem with long parameter lists
The earlier search method took three parameters: author, page, and size. Search endpoints tend to grow. Add a date filter, a genre filter, and a sort order, and the handler looks like this:
@GetMapping
public List<Book> search(@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) LocalDate since,
@RequestParam(required = false) List<String> genre) {
return service.search(author, page, size, since, genre);
}This has three problems. The signature is long and easy to get wrong, because several parameters share a type. The same list gets repeated on every endpoint that searches. Validation rules also have nowhere to live, because each rule would need its own annotation on its own parameter.
Spring can instead bind all the query parameters to one object. The object becomes a named, reusable, validatable description of the search.
Binding with a plain object parameter
A handler parameter that is not a simple type, and has no @RequestParam, @PathVariable, or @RequestBody, is treated as a model attribute. Spring creates the object and fills it from the request's query parameters (and form fields). Writing @ModelAttribute explicitly is optional and does the same thing.
import java.time.LocalDate;
import java.util.List;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.springframework.format.annotation.DateTimeFormat;
public record BookSearchCriteria(
String author,
@Min(0) Integer page,
@Min(1) @Max(100) Integer size,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
List<String> genre) {
public BookSearchCriteria {
page = (page == null) ? 0 : page;
size = (size == null) ? 20 : size;
genre = (genre == null) ? List.of() : genre;
}
}The controller method shrinks to one parameter:
@GetMapping
public List<Book> search(@Valid BookSearchCriteria criteria) {
return service.search(criteria);
}A request such as GET /api/books?author=Le%20Guin&size=10&genre=fantasy&genre=classic produces a criteria object with author set to Le Guin, page defaulted to 0, size set to 10, since set to null, and genre set to [fantasy, classic].
How the binding works
Spring's data binder matches each query parameter name to a name on the target class. For a record, the names come from the record components, and the binder calls the canonical constructor with the converted values. This is called constructor binding. The compact constructor then runs, so it is the right place for defaults.
Several rules follow from this model:
- Names must match exactly.
?pageSize=10does not bind to a component namedsize. Names are case-sensitive, andpage-sizedoes not map topageSize. - Unknown parameters are ignored. A request with
?foo=barsucceeds, andfoois dropped. Nothing fails on extra input. - Missing parameters become
null. For this reason the record usesIntegerrather thanint. The compact constructor turnsnullinto the default. This replaces@RequestParam(defaultValue = ...). - Conversion uses the same machinery as
@RequestParam. Numbers, enums, andUUIDwork out of the box. Dates need@DateTimeFormat, as in the earlier chapter. - Repeated parameters fill a collection.
?genre=fantasy&genre=classicgives a two-element list. A comma-separated value such as?genre=fantasy,classicalso splits into two elements, because the string-to-collection conversion splits on commas.
Renaming a parameter
To bind a query parameter whose name differs from the Java name, use @BindParam. It was added in Spring Framework 6.1:
import org.springframework.web.bind.annotation.BindParam;
public record SortCriteria(@BindParam("sort-by") String sortBy) {}On older versions you would need a setter-based class with a different property name, or @RequestParam on the handler.
Records versus classes with setters
A mutable class with a no-argument constructor and setters also works. The binder creates the object and calls a setter for each matching parameter.
public class LegacyCriteria {
private String author;
private int page = 0;
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public int getPage() { return page; }
public void setPage(int page) { this.page = page; }
}| Aspect | Record (constructor binding) | Class with setters |
|---|---|---|
| Defaults | Compact constructor | Field initializers |
| Mutability | Immutable after binding | Mutable, setters are public |
| Extra properties exposed | Only the declared components | Every setter is bindable |
| Missing primitive parameter | Use wrapper types and defaults | Keeps the field initializer value |
| Typical use | New code | Older code, Spring Data style types |
The "extra properties exposed" row matters for security. With setters, any public setter can be set by a client who adds the matching parameter. This is called mass assignment. If the class later gains a field such as adminOnly with a setter, a client can set it with ?adminOnly=true. A record's fixed set of components keeps the bindable surface the same as the declared API.
Validating the object
@Valid on the parameter triggers Bean Validation after binding. The constraints on the record components apply to the converted values: ?size=500 violates @Max(100) and fails.
Placing defaults in the compact constructor has one more benefit. Validation runs on the finished object, so @Min(1) on size sees 20 when the client omits it. The default is never rejected as null.
Validation cannot see the original text of a value that failed conversion. ?page=abc never reaches the constraints. Conversion fails first, and Spring records a type-mismatch error for the field page.
Errors from object binding
Object binding fails differently from @RequestParam:
| Input | `@RequestParam` handler | Query object handler |
|---|---|---|
| `?page=abc` | `MethodArgumentTypeMismatchException` | Field error of type `typeMismatch` on `page` |
| `?size=500` | Not checked unless the parameter is validated | Field error from `@Max` on `size` |
| Several bad values | Fails on the first one | All errors are collected together |
The object form collects every field error before it fails. In Spring 6.x the failure is raised as MethodArgumentNotValidException, which extends BindException. The handler from the earlier chapter already catches it:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.putIfAbsent(e.getField(), e.getDefaultMessage()));
problem.setProperty("errors", errors);
return problem;
}The only change is the detail text. "Request body failed validation" is wrong for a GET with no body, so the message now says "Request failed validation". Because the handler reads field errors from the BindingResult, it reports type mismatches and constraint violations the same way.
Try it:
curl -i "http://localhost:8080/api/books?page=abc&size=500"The response is a 400 with a ProblemDetail body. Its errors map should contain an entry for page (a conversion message) and an entry for size (the @Max message). The exact message text depends on your Spring version and locale, so do not hard-code it in clients.
Combining with other inputs
A query object can sit beside a path variable. Each parameter is resolved independently:
@GetMapping("/authors/{authorId}/books")
public List<Book> booksByAuthor(@PathVariable Long authorId,
@Valid BookSearchCriteria criteria) {
return service.searchByAuthor(authorId, criteria);
}Keep the two apart. The path variable identifies the resource, and the query object filters or shapes the result. Do not put a path variable's name into the record too, because a matching query parameter would then bind alongside it and confuse the meaning.
Common mistakes
- Adding
@RequestParamto the object. Spring then tries to convert one string intoBookSearchCriteriaand fails. Leave the annotation off, or use@ModelAttribute. - Using
@RequestBodyon a GET. This expects a JSON body, which GET requests normally do not carry. Query objects use query parameters. - Forgetting
@Valid. The constraints are on the record, but nothing checks them without@Valid(or@Validated) on the parameter. - Primitive components with missing parameters. Prefer wrapper types plus defaults in the compact constructor, so the "not supplied" case is explicit and testable.
- Overlapping names. If a record component and a
@PathVariableshare a name, only the path variable is guaranteed to come from the path. A query parameter with the same name can still bind to the record. - Treating defaults as validation. A default hides a missing value. If a parameter is required, use
@NotNulland leave it out of the compact constructor's defaults.
When to use a query object
Use one when an endpoint takes three or more query parameters, when several endpoints share the same filters, or when you want validation rules in one place. Keep @RequestParam for one or two simple, endpoint-specific parameters, where a separate type adds more ceremony than it removes.
Exercise
A client calls GET /api/books?size=0&since=yesterday against the search(@Valid BookSearchCriteria criteria) handler. What does the response contain, and why does the size constraint appear in the result even though since fails to convert?
Show answer
The response is a 400 ProblemDetail. Binding runs first: since=yesterday cannot be parsed as an ISO date, so the binder records a typeMismatch field error for since. The other values are still bound, and size=0 is converted to 0. Validation then checks @Min(1) on size and adds a second field error. Because the binder collects errors instead of stopping at the first, the errors map holds both since and size.
Exercise
Why does BookSearchCriteria use Integer page with a default in the compact constructor, instead of int page with @RequestParam(defaultValue = "0")-style behavior?
Show answer
Object binding has no defaultValue attribute. A missing parameter arrives as null, which cannot be stored in a primitive int. Using Integer makes the missing case visible, and the compact constructor replaces null with 0. Validation then runs on the finished object and sees the default.