@RequestBody、@RequestParam和@PathVariable的区别

@RequestBody、@RequestParam和@PathVariable的区别

一、注解之间的区别

  1. @RequsetParam是用于接收URL的查询串中的相应参数及请求体中的参数;
  2. @PathVariable 是用于接收URL中占位符的参数,@Requestmapper("/{id}")
  3. @RequestBody是用于接收post请求中form表单中的数据;

二、示例

1. @RequestParam 示例

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

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

接收请求体中的参数

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

@Controller
@RequestMapping("receive")
public class receiveTest {
    
    @RequestMapping("/receiveFile")
    @ResponseBody
    public String receiveFile(@RequestParam(required = false, value = "file") MultipartFile File, @RequestParam String param1, @RequestParam String param2) {
        return param1 + param2;
    }
}

2.@PathVariable 示例

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

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

3.@RequestBody示例

在post请求中,当访问URL为 localhost:8080/getproduct

@RequestMapping("/getproduct")
public Product getProduct(@RequestBody Product product){
	...//Product包含有一个 名字为 id的属性
}

posted on   Chase_Hanky  阅读(263)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示