新手向:一文搞懂RequestParam、PathVariable、RequestBody
@PathVariable
和@RequestParam
一般用于Get请求,分别是从路径里面去获取变量,也就是把路径当做变量,后者是从请求里面获取参数。RequestBody
一般用于Post请求,获取请求Body中的JSON数据
RequestParam
@ApiOperation(value = "用户测试", notes = "用户测试notes")
@GetMapping("localDateTime")
public ResultMessage localDateTimeGet(@RequestParam(value = "localDateTime") LocalDateTime localDateTime) {
return ResultMessage.success(localDateTime);
}
]
请求路径:http://localhost:9527/test/localDateTime?localDateTime=1627451273069
RequestParam
相当于把参数拼接到URL,多个参数间使用&连接,使用Postman请求时对应的是QueryParams。
如果请求参数不正确时,会报错:
MissingServletRequestParameterException: Required LocalDateTime parameter ‘localDateTime’ is not present。 即没找到请求的该参数,此时需要检查@RequestParam(value = “xxx”)的value值与请求参数名称是否一致。
PathVariable
@RequestMapping("/test")
@ApiOperation(value = "用户测试", notes = "用户测试notes")
@GetMapping("{localDateTime}")
public ResultMessage localDateTimePath(@PathVariable("localDateTime") LocalDateTime localDateTime) {
return ResultMessage.success(localDateTime);
}
请求路径:http://localhost:9527/test/1627451273069
在使用了PathVariable
注解的接口中,请求路径中的localDateTime
参数相当于一个占位符,补位的参数就是@PathVariable
后的值。
RequestBody
@ApiOperation(value = "用户测试", notes = "用户测试notes")
@PostMapping("localDateTime")
public ResultMessage localDateTimePost(@RequestBody LocalDateTimeVO localDateTimeVO) {
return ResultMessage.success(localDateTimeVO);
}
请求路径:http://localhost:9527/test/localDateTime
RequestBody
修饰的类:
@Data
public class LocalDateTimeVO {
private LocalDateTime localDateTime;
}
传递的数据:
{
"localDateTime": 1627453417913
}
官方文档解读
RequestBody
Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through anHttpMessageConverter
to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with@Valid
. 该注解主要是解析请求体中的数据,映射到后端接收数据的实体类中,即反序列化。
相关文章
- 【技术种草】cdn+轻量服务器+hugo=让博客“云原生”一下
- CLB运维&运营最佳实践 ---访问日志大洞察
- vnc方式登陆服务器
- 轻松学排序算法:眼睛直观感受几种常用排序算法
- 十二个经典的大数据项目
- 为什么使用 CDN 内容分发网络?
- 大数据——大数据默认端口号列表
- Weld 1.1.5.Final,JSR-299 的框架
- JavaFX 2012:彻底开源
- 提升as3程序性能的十大要点
- 通过凸面几何学进行独立于边际的在线多类学习
- 利用行动影响的规律性和部分已知的模型进行离线强化学习
- ModelLight:基于模型的交通信号控制的元强化学习
- 浅谈Visual Source Safe项目分支
- 基于先验知识的递归卡尔曼滤波的代理人联合状态和输入估计
- 结合网络结构和非线性恢复来提高声誉评估的性能
- 最佳实践丨云开发CloudBase多环境管理实践
- TimeVAE:用于生成多变量时间序列的变异自动编码器
- 具有线性阈值激活的神经网络:结构和算法
- 内网渗透之横向移动 -- 从域外向域内进行密码喷洒攻击