-- 创造无限可能

java接收参数 @RequestParam @PathVariable @RequestBody 有什么区别

2023-08-09 18:05:20
540 人浏览 0 人点赞
有用,点赞支持一下

@RequestParam:用于从请求参数中获取值,常用于GET请求,可以指定参数的名称和默认值。

@PathVariable:用于从URL路径中获取值,常用于RESTful风格的URL,可以指定参数的名称和默认值。

@RequestBody:用于从请求体中获取值,常用于POST请求,可以将请求体中的数据绑定到方法的参数上。

示例:

@PathVariable

接收链接上的参数
@PostMapping("/{currentPage}/{pageSize}")
@NoLoginRequired
public R text(@PathVariable Integer currentPage, @PathVariable Integer pageSize){

}

@RequestParam

接收get请求参数
@GetMapping("text")
public R text(@RequestParam Integer id){

}

@RequestBody

用HashMap接收json参数
@GetMapping("text")
public R text(@RequestBody HashMap<String, String> student){

    String studentId = student.get("studentId");
    String name = student.get("name");

}


用实体类接收json参数
@PostMapping("text")
public R text(@RequestBody Student student){

    String studentId = student.getStudentId;
    String name = student.getName;

}