@RequestParam、@RequestBody、@PathVariable区别和案例分析
一、前言
@RequestParam、@RequestBody、@PathVariable都是用于在Controller层接收前端传递的数据,他们之间的使用场景不太一样,今天来介绍一下!!
二、实体类准备
@Data
public class Test implements Serializable {
private String id;
private String name;
private String state;
private String createTime;
}
三、@RequestParam
- 定义
一个请求,可以有多个RequestParam
@RequestParam 接收普通参数的注解 一般与get请求一起使用 @RequestParam(value="参数名",required="true/false",defaultValue="如果没有本值为这个参数的值")
required默认为true,当为false是,才可以使用defaultValue
- 案例
@GetMapping("/getDataById")
public String getDataById(@RequestParam(value = "id",required = false,defaultValue = "1") String id){
//使用mybatis-plus来根据id查询数据
Test test = testMapper.selectById(id);
return test.toString();
//结果: Test{id='1', name='dd', state='A', createTime='null'}
}
四、@RequestBody
- 定义
一个请求,只有一个RequestBody
@RequestBody(required="true/false") @RequestBody:一般来接受请求体中json的注解 一般与post请求一起使用 required默认为true(比传,要不报错)
- 案例
@PostMapping("/insertData")
public int insertData(@RequestBody Test test){
//使用mybatis-plus来插入新数据
int insert = testMapper.insert(test);
return insert;
//结果: 1
}
五、@PathVariable
- 定义
一个请求,可以有多个PathVariable
@PathVariable 映射URL绑定的占位符 一般与get请求一起使用 @PathVariable(value="参数名",required="true/false")
- 案例
@GetMapping("/getById/{id}")
public String getById(@PathVariable String id){
//使用mybatis-plus来根据id查询数据
Test test = testMapper.selectById(id);
return test.toString();
//结果: Test{id='1', name='dd', state='A', createTime='null'}
}
六、区别和使用场景
@RequestParam一般在get请求时,参数是一个个的参数时,请求url一般为http://localhost:8089/test/getDataById?id=1 @RequestBody一般在post请求时,参数是一个对象或者集合时,请求一般为json类型的请求体 @PathVariable一般在get请求时,参数是一个个的参数时,更能体现RestFul风格,请求url一般为:http://localhost:8089/test/getDataById/1
有下面两段代码:
@RequestMapping("getUser/{id}")
public String GetUser(@PathVariable int id) {
return userService.findById(id).toString();
}
@RequestMapping(path = "/del")
public String del(@RequestParam(name = "user_id") Integer user_id) {
userService.delById(user_id);
return "redirect:/userlist";
}
@PathVariable是请求路径,是从路径中获取变量,也就是把路径当做变量。
@RequestParam是请求参数,就是获取参数的。
如下面两个例子:
地址1:http://localhost:8989/SSSP/emps?pageNo=3
地址2:http://localhost:8989/SSSP/emp/8
如果想获取地址1中的 pageNo的值 ‘3’ ,则使用 @RequestParam ,
如果想获取地址2中的 emp/8 中的 ‘8’ 则使用 @PathVariable