网站首页 > 精选文章 / 正文
一、前言
@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
Tags:java jsonpath
猜你喜欢
- 2025-06-09 Jmeter(二十):jmeter对图片验证码的处理
- 2025-06-09 警告!Kubernetes集群正在遭挖矿劫持,这一次目标是Kubeflow,微软ASC呼吁:不要随意更改默认设置
- 2025-06-09 王炸!程序员必备的JSON可视化工具!
- 2025-06-09 基于 Kubernetes 部署容器平台kubesphere
- 2025-06-09 前端如何做大量的数据校验?json schema配置详解
- 2025-06-09 从源码看Log4j2、FastJson漏洞(log4j info)
- 2025-06-09 深入解析 MySQL 8.0 JSON 相关函数:解锁数据存储的无限可能
- 2025-06-09 微服务测试的不同策略之测试Java微服务,看完秒懂
- 2025-06-09 如何统一处理 Spring Boot Web 请求的 JSON 日期格式
- 2025-06-09 一个基于C#开发的Excel转Json工具