In Spring MVC you can use the
@PathVariable annotation on a method argument to bind it to the
To process the @PathVariable annotation, Spring MVC needs to find the matching URI template
variable by name. You can specify it in the annotation:
A method can have any number of @PathVariable annotations:
The @RequestMapping annotation supports the use of regular expressions in URI template variables.
The syntax is {varName:regex} where the first part defines the variable name and the second - the
regular expression. For example:
value of a URI template variable:
@GetMapping("/owners/{ownerId}")
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}
To process the @PathVariable annotation, Spring MVC needs to find the matching URI template
variable by name. You can specify it in the annotation:
@GetMapping("/owners/{ownerId}")
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}
A method can have any number of @PathVariable annotations:
@GetMapping("/owners/{ownerId}/pets/{petId}")
public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
Pet pet = owner.getPet(petId);
model.addAttribute("pet", pet);
return "displayPet";
}
The @RequestMapping annotation supports the use of regular expressions in URI template variables.
The syntax is {varName:regex} where the first part defines the variable name and the second - the
regular expression. For example:
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}