@RequestBody、@RequestParam和@PathVariable的区别

@RequestBody、@RequestParam和@PathVariable的区别

一、注解之间的区别

@RequestParam 和 @PathVariable 一样,都是用于从request请求中绑定参数的,区别在于:

1:@RequestParam是用于接收URL的查询串中的相应的参数以及请求体中的参数;
2:@PathVariable是用于接收URL中占位符的参数
3:@RequestParam 和 @PathVariable 注解是用于从 request 中接收请求的,两个都可以接收参数,关键点不同的是 @RequestParam 是从 request 里面拿取值,而 @PathVariable 是从一个 url 模板里面来填充。
4:@RequestParam 注解是获取静态 url 传入的参数
@PathVariable 是获取请求路径中的变量作为参数,需要和 @RequestMapping(“item/{itemId}”) 配合使用。

@RequestBody和 @RequestParam区别在于:

1:@RequestParam是用于接收URL的查询串中的相应的参数以及请求体中的参数;
2:@RequestBody是用于接收post请求中form表单中的数据,用来接收前端传递给后端的 json 字符串中的数据(请求体中的数据);
3:在 Get 请求中,不能使用 @RequestBody。 在 Post 请求,可以使用 @RequestBody 和 @RequestParam,但是如果使用 @RequestBody,对于参数转化的配置必须统一。
4:@RequestParam 注解接收的参数是来自于 requestHeader 中,即请求头。都是用来获取请求路径 url 中的动态参数。也就是在 url 中,格式为 xxx?username=123&password=456。
@RequestBody 注解接收的参数则是来自于 requestBody 中,即请求体中。
Get 方式无请求体,所以使用 @RequestBody 接收数据时,前端不能使用 Get 方式提交数据;
而是使用 Post 方式进行提交的。在后端的同一个接收方法里,@RequestBody 与 @RequestParam() 可以同时使用; @RequestBody 最多只能有一个,而 @RequestParam() 可以有多个。

二、注解示例

1. @RequestParam 示例

接收请求行中URL后的查询串参数,当访问URL为 localhost:8080/demo1?name=Aaron&age=18时,将会把查询串中的参数按名绑定到demo1方法的相应形参上, 接收请求体中的参数

@RequestMapping(value = "/demo1")
public void demo1(@RequestParam String name,@RequestParam int age) {

}

当请求头中的 Content-Type 类型为:multipart/form-data 或 application/x-www-form-urlencoded 时,该@RequestParam注解同样可以把请求体中相应的参数绑定到Controller方法的相应形参中

2.@PathVariable 示例

现有Controller如下,当访问URL为 localhost:8080/demo2/Bob/12时,将会把URL占位符的的参数按名绑定到demo2方法的相应形参上

@RequestMapping(value = "/demo2/{name}/{id}")
public void demo2(@PathVariable String name,@PathVariable int id) {

}

3.@RequestBody示例

在post请求中,当访问URL为 localhost:8080/getproduct,而且post的部分数据为{id:32}

参考链接:

https://blog.csdn.net/weixin_49770443/article/details/109311246
https://blog.csdn.net/qq_32683235/article/details/113878052
posted @ 2022-05-13 19:44  Cloverlove  阅读(938)  评论(0编辑  收藏  举报