What is the purpose of the @PathVariable annotation in Spring MVC?
A) To bind a URI template variable to a method parameter
B) To inject dependencies into a controller
C) To configure view resolvers
D) To handle exceptions in a controller
Answer:
A) To bind a URI template variable to a method parameter
Explanation:
The @PathVariable
annotation in Spring MVC is used to bind a URI template variable to a method parameter. This allows you to extract values from the URI and pass them as arguments to the handler method.
For example:
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") String userId, Model model) {
model.addAttribute("userId", userId);
return "userProfile";
}
}
In this example, the @PathVariable("id")
annotation binds the value of the id
variable in the URI to the userId
method parameter. When a request is made to /users/123
, the userId
parameter will be set to “123”, and the getUserById
method will return the “userProfile” view with the userId attribute set.
The @PathVariable
annotation is particularly useful for RESTful web services where resources are identified by unique identifiers in the URI.