How to use @PathVariable and @PathParam in Spring MVC?
In Spring MVC, @PathParam and @PathVariable are annotations used to extract parameters from a URL path. They can be used to bind variables from the URL path to method parameters.
Utilizing @PathParam:
- In the parameter list of the controller method, use the @PathParam annotation to specify the variable name to be extracted from the URL path.
- In the @RequestMapping annotation, use curly braces {} to represent variables in the URL path.
- In the method body, you can directly use parameters annotated with @PathParam to retrieve variable values from the URL path.
The example code is provided below:
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public String getUser(@PathParam("userId") String userId) {
// 根据userId获取用户信息
return "user";
}
}
Use @PathVariable:
- In the parameter list of a controller method, use the @PathVariable annotation to specify the variable name to extract from the URL path.
- In the @RequestMapping annotation, use curly brackets {} to represent variables in the URL path.
- In the method body, you can directly use parameters annotated with @PathVariable to retrieve variable values from the URL path.
Here is an example code:
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public String getUser(@PathVariable("userId") String userId) {
// 根据userId获取用户信息
return "user";
}
}
Both @PathParam and @PathVariable can be used to extract parameters from the URL path. They function in a similar way, just with different annotation names.