@PathVariable Example in Spring MVC

In this Spring MVC tutorial, you will learn how to use a @PathVariable parameter to read the path parameter value.

Let’s say we have the following URL:

http://localhost:8080/api/users/5jg8hf4ys9fit

If we break the above URL down into smaller parts then we will see that:

  • HTTP – is the protocol being used,
  • localhost  – is the domain name,
  • 8080 – is the port number,
  • api – is the root path of your web services application,
  • users – is most likely the @Path value of your Root Resource class and,
  • 5jg8hf4ys9fit – is the is the path parameter value which we can use with @PathVariable annotation.

So how do we read the value of 5jg8hf4ys9fit from the URL path using the @PathVariable annotation?

@PathVariable. Reading URL Path Parameters.

Here is an example of @RestController class that uses @GetMapping and @PathVariable annotation to handle HTTP Get request and read the value of path parameter from the URL mentioned above.

  • Use @GetMapping to define path value, like so:
    @GetMapping(path = "/{userId}")
  • Use @PathVariable to read the path parameter value and make it available as a method argument
    public UserRest getUser(@PathVariable String userId)

@RestController class example:

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;
 
    @GetMapping(path = "/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public UserRest getUser(@PathVariable String userId) {

        UserRest returnValue = new UserRest();

        UserDto userDto = userService.getUser(userId);
        BeanUtils.copyProperties(userDto, returnValue);

        return returnValue;
    }

}

I hope this example was helpful to you. Check out the below video courses if you are interested to learn more about Spring MVC framework.