@Param、@PathVariable 和 @RequestParam的使用场景和区别

发布时间 2023-06-07 21:07:05作者: MindHunter

@Param、@PathVariable 和 @RequestParam的使用场景和区别

  • @Param 注解:
    使用框架:MyBatis(持久层框架),一般只在xxxmapper.java上使用,当传输的数据超过一个时,需要使用它来取别名,否则数据库无法区分
    用途:指定方法参数与 SQL 查询参数的对应关系。
    场景:在 MyBatis 中,@Param 注解用于给方法参数取一个自定义的名称,然后在 SQL 语句中使用该名称来引用对应的参数值。
示例:
@GetMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable("houseId") Integer houseId, @PathVariable("type") Integer type, Model model){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        return PAGE_UPLOAD_SHOW;
}

xxxmapper.java
List<HouseImage> findHouseImageByHouseId(@Param("houseId") Integer houseId, @Param("type") Integer type);
  • @PathVariable 注解:
    使用框架:Spring MVC(Web框架)
    用途:从请求的 URL 中获取路径变量的值。
    场景:在 RESTful API 中,用于提取 URL 路径中的参数。
示例:
@GetMapping("/users/{id}")
public User getUserById(@PathVariable("id") int id) {
    // 处理获取到的路径变量值
}
  • @RequestParam 注解:
    使用框架:Spring MVC(Web框架)
    用途:从请求的 URL、表单数据或查询参数中获取请求参数的值。主要获取表单中传输的数据(数据内的数据)
    场景:用于处理普通的表单提交或查询字符串参数。
示例:
@GetMapping("/users")
public User getUserById(@RequestParam("id") int id) {
    // 处理获取到的请求参数值
}

总结:

@Param 注解主要用于 MyBatis 中,用于指定方法参数与 SQL 查询参数的对应关系。
@PathVariable 注解主要用于 Spring MVC 中,用于从 URL 路径中获取路径变量的值。
@RequestParam 注解主要用于 Spring MVC 中,用于从 URL、表单数据或查询参数中获取请求参数的值。