How to read path variables with @PathVariable annotation in Spring Boot
In this tutorial we are going to learn about reading a path variable with the annotation @PathVariable which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.
Now we will work with the get user method and learn about reading the user Id from the URL path.
If I want to get a resource or single user details, then we need to provide user Id in the URL i.e. http://localhost:8080/users/123 and this user Id is going to be a path variable because user Id is different for each user.
Let’s get back to our get user method in rest controller, this entire class is mapped to http://localhost:8080/users and based on the HTTP request that is sent. The appropriate HTTP method will be triggered.
Now create a binding for the get user method in the controller class by adding path to the @GetMapping annotation i.e. user Id and to read this value we need to add a method argument which will start with an annotation called @PathVariable.
Sample Code Snippet:
package com.behindjava.tutorial.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping(path="/userId")
public String getUser(@PathVariable String userId) {
return "USER FETCHED WITH THE USER ID:"+userId;
}
}
You can test this HTTP get method using postman as below.