新手向:一文搞懂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);
    }

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
@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

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 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-20210728143051227

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值