Sub topic 4
Reading query parameters with @RequestParam
This chapter assumes you can run a Spring Boot web project (spring-boot-starter-web), know what a controller method is, and understand HTTP methods and status codes. You should also be comfortable with Java records and basic generics.
What a query parameter is
A query parameter is a name and value pair placed after the ? in a URL. Several pairs are joined with &:
/api/books?author=Le%20Guin&page=1&size=10The part after ? is the query string. Values are URL-encoded, so a space becomes %20 (or + in form-style encoding). Spring decodes the values before it hands them to your method.
Query parameters suit input that refines or modifies a request without identifying a single resource: filters, paging, sorting, and flags. The path says which collection you are reading. The query string says how to narrow it.
Binding by name with @RequestParam
@RequestParam binds one query parameter to one method parameter. By default Spring matches the Java parameter name to the query parameter name. This works because Spring Boot builds with the -parameters compiler flag, which keeps parameter names in the compiled class. Maven and Gradle projects created with the Spring Boot plugins have this enabled.
@GetMapping
public List<Book> search(@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return service.search(author, page, size);
}For the request GET /api/books?author=Le%20Guin&page=1, Spring calls search("Le Guin", 1, 20). The size parameter is absent, so its default applies.
If you want the Java name and the URL name to differ, name the parameter explicitly:
@GetMapping("/by-author")
public List<Book> byAuthor(@RequestParam("author-name") String authorName) {
return service.search(authorName, 0, 20);
}Naming it explicitly is also safer if the code might be compiled without -parameters.
Required, optional, and default values
The attributes of @RequestParam control what happens when the parameter is missing.
| Declaration | Request lacks the parameter | Result |
|---|---|---|
| `@RequestParam String author` | Yes | 400 Bad Request |
| `@RequestParam(required = false) String author` | Yes | `author` is `null` |
| `@RequestParam(defaultValue = "0") int page` | Yes | `page` is `0` |
| `@RequestParam Optional<String> author` | Yes | `Optional.empty()` |
A parameter is required by default. When a required parameter is missing, Spring throws MissingServletRequestParameterException, which the default handling maps to a 400 response.
Three details cause most of the confusion:
- Setting
defaultValuemakes the parameter optional. You do not needrequired = falseas well. - The default value is always a string, because it goes through the same conversion as a value from the URL.
defaultValue = "0"is correct for anint. - A default applies when the parameter is absent and also when it is present but empty.
?page=is treated as missing, sopagebecomes0.
A primitive parameter such as int page cannot hold null. If you mark it required = false without a default and the client omits it, Spring fails with an error because it cannot convert null to int. Use a wrapper type (Integer) or supply a default.
@GetMapping("/optional-page")
public List<Book> optionalPage(@RequestParam(required = false) Integer page) {
int effectivePage = (page != null) ? page : 0;
return service.search(null, effectivePage, 20);
}Converting values to Java types
Every query parameter arrives as a string. Spring converts it to the type you declared. Built-in conversion covers numbers, booleans, enums, UUID, and many other types.
A failed conversion, such as ?page=abc for an int, throws MethodArgumentTypeMismatchException. Spring maps that to a 400 response. The chapter on binding errors shows how to customize the body.
Dates and times need a format hint, because many formats are possible. Use @DateTimeFormat:
@GetMapping("/published")
public List<Book> publishedSince(
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since) {
return service.publishedSince(since);
}With this declaration, ?since=2024-05-01 becomes LocalDate.of(2024, 5, 1). A value in another format, such as 05/01/2024, fails conversion and produces a 400.
Enums
Enum conversion matches the constant name exactly and is case-sensitive by default:
public enum SortOrder { ASC, DESC }
@GetMapping("/sorted")
public List<Book> sorted(@RequestParam(defaultValue = "ASC") SortOrder order) {
return service.sorted(order);
}?order=DESC works. ?order=desc fails with a 400 unless you register a case-insensitive converter.
Repeated and multi-valued parameters
A query string may repeat a name: ?tag=fantasy&tag=classic. Declare a List or an array to receive all the values:
@GetMapping("/tagged")
public List<Book> tagged(@RequestParam List<String> tag) {
return service.byTags(tag);
}Spring also accepts the comma-separated form ?tag=fantasy,classic for a List or array and splits it for you. This means a single value that contains a comma is split into two. If your values can contain commas, use the repeated form and take care with how the client encodes them.
To capture every parameter without knowing the names in advance, use a Map:
@GetMapping("/raw")
public Map<String, String> raw(@RequestParam Map<String, String> all) {
return all;
}With a Map<String, String>, only the first value of a repeated name is kept. Use MultiValueMap<String, String> to keep all values.
How the request flows
The diagram shows what happens between the HTTP request and your method call.
Calling the endpoint
You can try the search endpoint with curl. Quote the URL, because the shell treats & as a command separator.
curl "http://localhost:8080/api/books?author=Le%20Guin&page=0&size=10"
curl "http://localhost:8080/api/books?page=abc"The first call returns the matching books. The second fails conversion and returns a 400.
Common errors
- Unquoted URLs in the shell. Without quotes, everything after
&runs as a separate command. The server then sees only the first parameter. - Primitive with no default. An optional
intthat receives no value raises a conversion error. UseIntegeror a default. - Missing
-parameters. If implicit names fail with anIllegalArgumentExceptionabout a missing parameter name, name the parameter in the annotation or enable the compiler flag. - Confusing
@RequestParamwith@PathVariable. A value in/books/42is a path variable. A value in?id=42is a query parameter. Each annotation reads only its own source. - Form bodies.
@RequestParamalso reads fields from a form-encoded body (application/x-www-form-urlencoded). It does not read JSON bodies. Use@RequestBodyfor those. - No upper limit on
size. A client can send?size=1000000. Cap paging values in the service or validate them, as a later chapter explains.
Exercises
Exercise
A handler declares @RequestParam int page with no other attributes. What status code does the client receive for GET /api/books and for GET /api/books?page=two, and why?
Show answer
Both return 400 Bad Request. The first omits a required parameter, so Spring throws MissingServletRequestParameterException. The second sends a value that cannot be converted to int, so Spring throws MethodArgumentTypeMismatchException.
Exercise
Write a handler for GET /api/books/by-tags that accepts any number of tag parameters, treats the parameter as optional, and passes an empty list to service.byTags when no tag is given.
Show answer
@GetMapping("/by-tags") public List<Book> byTags(@RequestParam(required = false) List<String> tag) { List<String> tags = (tag != null) ? tag : List.of(); return service.byTags(tags); }