Sub topic 5
Reading path variables and query parameters
This chapter shows how Spring MVC copies pieces of the request URL into controller method arguments. It assumes you can write a basic @RestController with @GetMapping, as covered earlier, and that you know what a URL path and a query string are.
Two places for data in a URL
A URL carries data in two places:
- The path identifies a resource. In
/api/authors/7/books/42, the numbers 7 and 42 pick out one author and one book. - The query string refines or modifies a request. In
?title=dune&year=1965, the parameters filter a collection.
A rule of thumb: if removing the value would point at a different resource, it belongs in the path. If removing it only widens or narrows the result, it belongs in the query string.
Spring handles each with its own annotation. @PathVariable reads a {placeholder} from the mapping template. @RequestParam reads a query parameter.
Path variables
A path variable is a named placeholder in curly braces inside the mapping. The class-level and method-level paths are joined, and placeholders from both are available to the method.
package com.example.books;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.format.annotation.DateTimeFormat;
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/authors/{authorId}/books")
public class AuthorBookController {
private final BookQueries queries;
public AuthorBookController(BookQueries queries) {
this.queries = queries;
}
@GetMapping("/{bookId:\\d+}")
public BookResponse get(@PathVariable long authorId,
@PathVariable("bookId") long id) {
return queries.find(authorId, id);
}
@GetMapping
public List<BookResponse> list(
@PathVariable long authorId,
@RequestParam(defaultValue = "") String title,
@RequestParam Optional<Integer> year,
@RequestParam(name = "tag", required = false) List<String> tags,
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate publishedAfter) {
return queries.search(authorId, title, year.orElse(null), tags, publishedAfter);
}
}
interface BookQueries {
BookResponse find(long authorId, long bookId);
List<BookResponse> search(long authorId, String title, Integer year,
List<String> tags, LocalDate publishedAfter);
}
record BookResponse(long id, String title, String author) {}Several things happen in this controller.
Name matching. @PathVariable long authorId binds to the placeholder {authorId} because the names are equal. This relies on the compiler keeping parameter names, which means the -parameters flag. The Spring Boot Maven parent and the Spring Boot Gradle plugin both enable it. If you build without them, write the name explicitly, as in @PathVariable("bookId"). The explicit form is also useful when the Java name and the placeholder should differ.
Type conversion. The path segment is a string. Spring converts it to long before your method runs. If the conversion fails, your method is never called.
Regular expressions. {bookId:\\d+} restricts the placeholder to digits. The Java string needs a doubled backslash. A request for /api/authors/7/books/abc then fails to match this mapping and returns 404, instead of reaching the method and failing conversion.
Specific beats general. If you also had a mapping for /api/authors/{authorId}/books/featured, Spring would choose the literal path over the placeholder for that URL. You do not need to order the methods.
Query parameters
@RequestParam reads from the query string. For a form-encoded POST body, it also reads the form fields. Its attributes control what happens when the parameter is absent:
| Declaration | Request lacks the parameter | Notes |
|---|---|---|
| `@RequestParam String title` | 400 Bad Request | `required` defaults to `true`. |
| `@RequestParam(defaultValue = "") String title` | Method receives `""` | A default value makes the parameter optional. |
| `@RequestParam(required = false) Integer year` | Method receives `null` | Use a wrapper type, not `int`. |
| `@RequestParam Optional<Integer> year` | Method receives `Optional.empty()` | Spring treats `Optional` as not required. |
The default value is itself a string that goes through the same conversion as the request value, so defaultValue = "20" works for an int.
Repeated and list parameters
The tags parameter has the type List<String>. Spring fills it from either style of request:
curl "http://localhost:8080/api/authors/7/books?tag=sf&tag=classic"
curl "http://localhost:8080/api/authors/7/books?tag=sf,classic"Both give a list of two items. A comma inside a single value is split into separate elements. If a tag can legitimately contain a comma, use the repeated form and be aware that the split still applies to each value in the list.
Dates and other formatted types
LocalDate has no single obvious text format, so you declare one. @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) accepts 2024-03-15. Types such as long, boolean, UUID and enums convert without extra annotations.
Reading every parameter
When the set of parameters is open-ended, bind them all to a map:
@GetMapping("/debug")
public java.util.Map<String, String> debug(
@RequestParam java.util.Map<String, String> all) {
return all;
}With Map<String, String> only the first value of a repeated parameter is kept. Use MultiValueMap<String, String> to keep them all. Prefer named parameters for anything you document, because a map hides the API contract.
What goes wrong and how it appears to clients
Binding failures happen before your method runs, so they are reported by Spring MVC itself.
| Situation | Exception | Status |
|---|---|---|
| Required parameter missing | `MissingServletRequestParameterException` | 400 |
| Value cannot convert, such as `?year=abc` | `MethodArgumentTypeMismatchException` | 400 |
| Path regex does not match, or no mapping fits | none, no handler found | 404 |
| Constraint annotation violated (see below) | `HandlerMethodValidationException` | 400 |
If you set spring.mvc.problemdetails.enabled=true, as shown in the error-handling chapter, the first two return a ProblemDetail body. You can also add your own @ExceptionHandler for MethodArgumentTypeMismatchException to name the offending parameter in the message:
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleBadParam(MethodArgumentTypeMismatchException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Parameter '" + ex.getName() + "' has an invalid value");
problem.setTitle("Invalid parameter");
return problem;
}Place this method in your @RestControllerAdvice class.
Validating parameters
Bean Validation constraints work directly on parameters. This is useful for page sizes and ranges:
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@GetMapping("/page")
public List<BookResponse> page(
@PathVariable long authorId,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return queries.search(authorId, "", null, null, null)
.stream().skip((long) page * size).limit(size).toList();
}The behavior depends on your version:
- Spring Framework 6.1 and later (Spring Boot 3.2 and later) validate constrained method parameters natively. A violation throws
HandlerMethodValidationException, which becomes a 400. Do not add@Validatedto the class in this setup. - Older versions need
@Validatedon the controller class. A violation then throwsConstraintViolationException, which returns 500 unless you handle it.
Edge cases worth knowing
- Trailing slashes. Since Spring Framework 6,
/api/books/does not match a mapping for/api/books. Clients that add a slash get 404. - File extensions. Suffix pattern matching is gone. A request such as
/files/report.pdfbindsreport.pdfto{name}in full, with no truncation. - Encoding. Spring decodes percent-encoded values before conversion. A
/sent as%2Finside a path variable is rejected by default by the servlet container for security reasons, so avoid slashes in identifiers. - Case. Parameter names and path literals are case-sensitive.
?Year=1965does not bind toyear. - Unknown parameters. Extra query parameters are ignored silently. A misspelled optional name such as
?yaer=1965returns unfiltered results with no error. - Sensitive data. Query strings end up in access logs and browser history. Do not carry passwords or tokens in them.
Exercise
A client calls GET /api/authors/7/books?year=19x5. The handler declares @RequestParam Integer year. Is the controller method invoked, and what status does the client get?
Show answer
The method is not invoked. Conversion from "19x5" to Integer fails with MethodArgumentTypeMismatchException, which Spring MVC maps to 400 Bad Request.
Exercise
Write the signature of a handler for GET /api/authors/{authorId}/books that takes a required long authorId from the path, an optional String title that defaults to an empty string, and a size between 1 and 100 that defaults to 20. Assume Spring Boot 3.2 or later.
Show answer
public List<BookResponse> list(@PathVariable long authorId, @RequestParam(defaultValue = "") String title, @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size). No class-level @Validated is needed, and a size of 0 or 101 produces a 400 through HandlerMethodValidationException.