A path variable is a value written inside the URL itself, such as the 5 in /students/5. In the mapping you write a placeholder like /students/{id}, and @PathVariable captures the real value and passes it into the controller method. It is used to identify a specific resource (one student, one order, one course) in clean, readable REST URLs. Spring also converts the text to the parameter’s type, so "5" becomes a Long automatically.
Types
- Single variable:
/students/{id}with@PathVariable Long id. - Explicit name:
@PathVariable("courseName") String course, when the variable and the parameter names differ. - Multiple variables:
/students/{id}/courses/{courseName}. - Regex constraint:
/students/{id:[0-9]+}, so only digits match. - Optional variable:
@PathVariable(required = false)orOptional<Long>, paired with two mappings. - All variables as a Map:
@PathVariable Map<String, String> vars.
