zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

2023-04-18 14:06:36 时间

@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 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. 该注解主要是解析请求体中的数据,映射到后端接收数据的实体类中,即反序列化。