Sub topic 4
Reading query parameters with @RequestParam
This chapter assumes you have a running Spring Boot web project (spring-boot-starter-web), know basic Java, and understand HTTP methods and status codes. You should also have seen @PathVariable in the previous chapter.
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 &. In /api/books?author=Le%20Guin&page=1, the names are author and page. Special characters are percent-encoded, so %20 is a space.
Query parameters suit optional input such as filters, sorting, and paging. They describe how to view a collection, not which single resource you want.
Binding by name
@RequestParam binds a query parameter to a method parameter. By default Spring matches the Java parameter name to the query parameter name.
@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);
}This method sits in the BookController mapped to /api/books. Three behaviors apply here:
authoris optional. If it is absent, the method receivesnull.pageandsizefall back to0and20when absent.- A request such as
GET /api/books?author=Le%20Guin&page=1givesauthorthe decoded valueLe Guin,pagethe value1, andsizethe default20.
Required, optional, and defaults
A parameter is required by default. If a required parameter is missing, Spring rejects the request with a 400 response before your method runs.
You have three ways to make a parameter optional:
| Approach | Missing value becomes | Example |
|---|---|---|
| `required = false` | `null` | `@RequestParam(required = false) String author` |
| `defaultValue` | the default, converted to the type | `@RequestParam(defaultValue = "20") int size` |
| `Optional<T>` | `Optional.empty()` | `@RequestParam Optional<String> author` |
Setting defaultValue makes the parameter optional automatically, so you do not need required = false as well. A primitive such as int cannot hold null. Without a default, a missing optional int fails, so give primitives a default or use Integer.
Naming the parameter explicitly
When the query name is not a valid Java identifier, or you do not want the URL tied to a Java variable name, set the name explicitly:
@GetMapping("/by-writer")
public List<Book> byWriter(@RequestParam("writer-name") String writerName) {
return service.search(writerName, 0, 20);
}Spring Boot's Maven and Gradle plugins compile with -parameters, so implicit names work in a standard project. If you build some other way, implicit names can fail, and explicit names always work.
Converting types
Query values arrive as strings, and Spring converts them to the declared type. Numbers, booleans, and enums work out of the box. Dates need a format hint:
@GetMapping("/published")
public List<Book> publishedSince(
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since) {
return service.publishedSince(since);
}@DateTimeFormat tells Spring how to parse ?since=2024-05-01 into a LocalDate. If conversion fails, for example with ?page=abc, Spring raises MethodArgumentTypeMismatchException, which becomes a 400 response.
Repeated and multiple values
To accept ?tag=java&tag=spring, declare a List:
@GetMapping("/tagged")
public List<Book> tagged(@RequestParam List<String> tag) {
return service.findByTags(tag);
}A comma-separated value such as ?tag=java,spring is also split into a list.
Common mistakes
- Using a primitive without a default for an optional parameter.
- Forgetting to URL-encode values that contain spaces or
&when building requests by hand. - Putting a required piece of identity, such as a book id, in a query parameter instead of the path.
Try the search endpoint:
curl "http://localhost:8080/api/books?author=Le%20Guin&page=0&size=10"Quote the URL in the shell, or & will be read as a background-job operator.
Exercise
A handler declares @RequestParam int size with no default and no required = false. What happens for a request to /api/books with no size, and for /api/books?size=ten?
Show answer
With no size, the parameter is required and missing, so Spring returns 400 before calling the method. With size=ten, conversion to int fails with MethodArgumentTypeMismatchException, which is also a 400 response by default. Adding defaultValue = "20" fixes only the first case.
Exercise
Write the parameter declaration for an optional sort query parameter that defaults to the string title.
Show answer
@RequestParam(defaultValue = "title") String sort