Spring MVC 中 @PathVariable 注解获取 URL 路径变量
@PathVariable 注解是 Spring MVC 中常用的注解之一,它可以用来获取 URL 路径中变量的值。
例如,在以下 URL 中:
/users/123
可以使用 @PathVariable 注解获取 123 这个值,代码如下:
@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId") Long userId) {
// 使用 userId 获取用户信息
return userService.getUser(userId);
}
在这个例子中,@PathVariable("userId") 注解表明了要从 URL 中获取名为 userId 的变量值。
@PathVariable 注解的优点在于:
- 可以方便地从 URL 中获取参数值。
- 可以提高代码的可读性和可维护性。
- 可以避免使用 RequestMapping 中的正则表达式来匹配 URL。
在使用 @PathVariable 注解时需要注意以下几点:
- URL 路径中的变量名必须与注解中的参数名一致。
- 可以使用
@PathVariable注解的value属性来指定参数名,例如:@PathVariable(value = "id")。 - 如果 URL 路径中没有指定变量名,则默认使用参数名作为变量名。
- @PathVariable 注解可以与其他注解一起使用,例如 @GetMapping、@PostMapping 等等。
原文地址: https://www.cveoy.top/t/topic/mXH1 著作权归作者所有。请勿转载和采集!