@PathVariable 和 @RequestParam 的区别

23 阅读1分钟

@PathVariableSpring MVC 中的一个注解,用于从 URL 路径中提取变量值,并将其绑定到方法的参数上。


例子:

@GetMapping("/{id}")
public String index(@PathVariable Long id) {
    // ...
}
  • @GetMapping("/{id}") 表示这个 URL 模板中有一个路径变量 {id}
  • @PathVariable Long id 会将 URL 中的 {id} 部分转换为 Long 类型,并赋值给方法的 id 参数。

示例说明:

假设你访问的 URL 是:
http://localhost:8080/123

那么:

  • Spring 会将 123 提取出来。
  • 将其转换为 Long 类型。
  • 传递给 index 方法的 id 参数。

扩展用法:

  1. 指定变量名(如果参数名与 URL 变量名不同):

    @GetMapping("/{userId}")
    public String getUser(@PathVariable("userId") Long id) {
        // ...
    }
    
  2. 多个路径变量

    @GetMapping("/users/{userId}/posts/{postId}")
    public String getPost(@PathVariable Long userId, 
                          @PathVariable Long postId) {
        // ...
    }
    

@RequestParam 的区别:

  • @PathVariable 是从 URL 路径中获取值(如 /users/123)。
  • @RequestParam 是从 查询参数中获取值(如 /users?id=123)。

简单总结:

@PathVariable 用于将 URL 中的占位符(如 {id})映射到方法参数,是构建 RESTful API 时常用的注解。