Mastering Spring’s @PathVariable: Real‑World Examples and Advanced Tips
This article explains the purpose and usage of Spring MVC’s @PathVariable annotation, covering basic binding, custom names, class‑level variables, multiple parameters, map injection, regex and optional variables, path‑suffix handling, and how to retrieve variables outside controllers, all with clear code examples.
1. Introduction
@PathVariable is a crucial Spring MVC annotation that binds URI template variables to method parameters, enabling clean RESTful URL handling and improving code readability and maintainability.
2. Practical Examples
2.1 Basic Usage
For the mapping to work, the URI variable name must match the method parameter name.
<code>@GetMapping("/{id}")
public Object id(@PathVariable Long id) {
return id;
}</code>2.2 Different Parameter Names
Specify the URI variable name in the annotation to avoid errors when the method parameter name differs.
<code>@GetMapping("/{id}")
public Object id(@PathVariable("id") Long key) {
return key;
}</code>2.3 Class‑Level Path Variables
<code>@RestController
@RequestMapping("/pv/{type}")
public class PathVariableController {
@GetMapping("/{id}")
public Object id(@PathVariable Integer type,
@PathVariable("id") Long key) {
return type + "@" + key;
}
}</code>The type variable matches the class‑level template, so no explicit name is needed.
2.4 Multiple URI Variables
<code>@GetMapping("/{cate}/{id}")
public Object category(@PathVariable String cate,
@PathVariable Long id) {
return cate + "@" + id;
}</code>You can define as many variables as the GET request size permits.
2.5 Map Receiving Path Variables
<code>@GetMapping("/api/{tag}/query/{name}")
public String getByTagAndName(@PathVariable Map<String, String> paths) {
String tag = paths.get("tag");
String name = paths.get("name");
return tag + "@" + name;
}</code>2.6 Regex Path Variables
<code>@GetMapping("/vk/api/{name:[a-z]+}")
public String getJarFile(@PathVariable String name) {
return name;
}</code>The variable matches only lowercase alphabetic strings.
2.7 Optional Path Variables
<code>@GetMapping({"/users/{id}", "/users/"})
public Object byId(@PathVariable Optional<Long> id) {
return id.orElseGet(() -> -1L);
}</code>If the id segment is missing, the method returns -1 .
2.8 Path Suffix Handling
When suffix matching is enabled, the suffix is stripped; use a regex to retain it.
<code>@GetMapping("/ext/api/{file:.+}")
public Object fileExt(@PathVariable String file) {
return new R(file);
}</code>2.9 Accessing Path Variables Outside Controllers
<code>private HttpServletRequest request;
public void uriVar() {
Map<String, String> vars = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
// vars now contains all path variables
}</code>Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.