@PathVariable binds a part of the request URL path to a method parameter in a Spring MVC controller. If a mapping is /users/{id}, then @PathVariable Long id receives the value in the URL, so /users/42 gives id = 42. It is how you build resource-style REST URLs such as /orders/17/items/3.
Spring converts the string segment to the parameter type for you, and returns 400 Bad Request if the conversion fails.
Declare a placeholder in curly braces in the mapping and match it with a parameter.
A request to GET /users/42 calls get(42L). When the parameter name equals the placeholder name, you can omit the annotation value. This relies on the -parameters compiler flag, which Spring Boot's Maven and Gradle plugins enable by default.
If the names differ, or you build without -parameters, name the variable.
You can capture several variables, or all of them at once into a Map<String, String>.
Prefer individual typed parameters; the map is useful for generic handlers.
A path variable is required by default. If it is missing, the mapping does not match. Mark one as optional with required = false or Optional, and map both URLs.
In Spring Boot 3 and Spring Framework 6, trailing slash matching is off by default, so /products/ no longer matches /products.
Spring converts the segment with its ConversionService: numbers, UUID, enums, LocalDate with @DateTimeFormat, and more.
GET /invoices/abc fails conversion and returns 400. To validate values, add @Validated on the controller and constraints on the parameter.
In Spring Framework 6.1 and later, built-in method validation can also handle this without @Validated. A violation then produces a HandlerMethodValidationException, which Spring maps to 400.
You can restrict what a variable matches inline.
Dots are handled carefully: suffix pattern matching is disabled by default since Spring 5.3, so /files/report.pdf keeps the extension in the value. A catch-all segment can be written with {*path}.
| Aspect | @PathVariable | @RequestParam |
|---|---|---|
| Location | URL path segment | Query string or form field |
| Example | /users/42 | /users?id=42 |
| Required by default | Yes | Yes |
| Typical use | Identify a resource | Filter, sort, paginate |
Use the path for the identity of a resource and query parameters for optional filters.
Spring raises a MethodArgumentTypeMismatchException and responds with 400 Bad Request.
Yes, the annotation works the same in annotated controllers on WebFlux.
The placeholder name does not match the parameter, or the code was built without -parameters. Name the variable explicitly.
No. URLs are logged by proxies and servers. Send secrets in headers or the request body.
@PathVariable extracts values from URI templates and converts them to Java types so controllers can expose clean resource URLs. Match names (or name them explicitly), use Optional for optional segments, and validate input so bad values yield a 400 response.