Spring @PathVariable Annotation Examples

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.

If the method parameter is Map<String, String> then the map is populated with all path variable names and values.

It is present in the Spring since 3.0.

1). Simple Mapping for @PathVariable

In this case an endpoint that identifies an entity with a primary key:

@GetMapping("/api/v1/students/{id}") @ResponseBody public String getStudentsById(@PathVariable String id) { return "id: " + id; }

2). Use @PathVariable with Specifying the Path Variable Name

Here we have to provide the name of the template path variable.The names for the method parameter and the path variable were the same.

@GetMapping("/api/v1/student/{id}") @ResponseBody public String getStudentById(@PathVariable("id") String studentId) { return "id: " + studentId; }

In Spring, method parameters annotated with @PathVariable are required by default

3). Use @PathVariable as Not Required

We can set the required property of @PathVariable to false to make it optional

@GetMapping(value = { "/api/v1/student", "/api/student/{id}" }) @ResponseBody public String getStudentById(@PathVariable(required = false) String id) { if (id != null) { return "id : " + id; } else { return "the id is missing"; } }

4). Use java.util.Optional for @PathVariable

We can use the java.util.Optional for the non-mandatory path variales.

@GetMapping(value = { "/api/v1/student", "/api/v1/student/{id}" }) @ResponseBody public String getStudentsById(@PathVariable Optional<String> id) { if (id.isPresent()) { return "id: " + id.get(); } else { return "the id is missing"; } }

5). Multiple Path Variables in a Single Request

We can pass multiple path variables in the request.Spring framework provides that facility to us.

@GetMapping("/api/v1/student/{id}/{className}") @ResponseBody public String getStudentByIdAndClass(@PathVariable String id, @PathVariable String className) { return "Id : " + id + ", class: " + className; }

6). Use Map for Path Variables

We can use java.util.Map<String, String> for handling multiple PathVariables.

@GetMapping("/api/v1/student/{id}/{className}") @ResponseBody public String getStudentsByIdClass(@PathVariable Map<String, String> map) { String id = map.get("id"); String className = map.get("className"); return "Id : " + id + ", class: " + className; } }

Post/Questions related to Spring @PathVariable Annotation

What is difference between @PathVariable and @RequestParam in spring?
What is difference between @PathParam and @PathVariable?
What is @ModelAttribute annotation in spring?
What is the use of @RequestParam annotation in spring?
What is @PathVariable in spring?
What is @ResponseBody in spring?
What is BindingResult in spring?
What is the Autowiring in spring?
What is difference between @service and @component?

In this article, we have seen Spring @PathVariable Annotation Examples.