How can you extract values from a URL using @PathVariable?

Extracting values from a URL with @PathVariable involves two steps: declaring a placeholder in the mapping annotation's URL pattern, and then binding that placeholder to a method parameter with @PathVariable. Spring handles matching the segment and converting it to the parameter's type.

Key Points

Example

For the mapping @GetMapping("/users/{userId}") with a parameter @PathVariable String userId, a request to /users/123 gives the method the value "123" directly, ready to pass into a service call.

@GetMapping("/users/{userId}")
public User getUser(@PathVariable String userId) {
    return userService.findById(userId);
}

Interview Tip

A concise interview answer is

I declare a placeholder in curly braces inside the mapping, like /users/{userId}, then bind it to a method parameter using @PathVariable, matching by name or with an explicit name if they differ. Spring converts the captured segment to the parameter's type automatically, so I can use it directly, like fetching a user by that ID.

Last updated: 16 July 2026

Previous question: What is the role of @PathVariable in Spring MVC?

Next question: What are the considerations when using @PathVariable in terms of URL design?

More Spring MVC (Optional) interview questions

All Spring MVC (Optional) questions