前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >新手向:一文搞懂RequestParam、PathVariable、RequestBody

新手向:一文搞懂RequestParam、PathVariable、RequestBody

作者头像
关忆北.
发布2021-12-07 16:53:14
9740
发布2021-12-07 16:53:14
举报
文章被收录于专栏:关忆北.

@PathVariable@RequestParam一般用于Get请求,分别是从路径里面去获取变量,也就是把路径当做变量,后者是从请求里面获取参数。 RequestBody一般用于Post请求,获取请求Body中的JSON数据

RequestParam
代码语言:javascript
复制
    @ApiOperation(value = "用户测试", notes = "用户测试notes")
    @GetMapping("localDateTime")
    public ResultMessage localDateTimeGet(@RequestParam(value = "localDateTime") LocalDateTime localDateTime) {
        return ResultMessage.success(localDateTime);
    }
image-20210728140009581
image-20210728140009581

]

请求路径:http://localhost:9527/test/localDateTime?localDateTime=1627451273069

RequestParam相当于把参数拼接到URL,多个参数间使用&连接,使用Postman请求时对应的是QueryParams。

如果请求参数不正确时,会报错:

MissingServletRequestParameterException: Required LocalDateTime parameter ‘localDateTime’ is not present。 即没找到请求的该参数,此时需要检查@RequestParam(value = “xxx”)的value值与请求参数名称是否一致。

PathVariable
代码语言:javascript
复制
@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后的值。

image-20210728141654950
image-20210728141654950
RequestBody
代码语言:javascript
复制
@ApiOperation(value = "用户测试", notes = "用户测试notes")
@PostMapping("localDateTime")
public ResultMessage localDateTimePost(@RequestBody LocalDateTimeVO localDateTimeVO) {
    return ResultMessage.success(localDateTimeVO);
}

请求路径:http://localhost:9527/test/localDateTime

RequestBody修饰的类:

代码语言:javascript
复制
@Data
public class LocalDateTimeVO {
    private LocalDateTime localDateTime;
}

传递的数据:

代码语言:javascript
复制
{
  "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 an HttpMessageConverter 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. 该注解主要是解析请求体中的数据,映射到后端接收数据的实体类中,即反序列化。

image-20210728142800144
image-20210728142800144
image-20210728143051227
image-20210728143051227
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • RequestParam
  • PathVariable
  • RequestBody
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档