@RequestBody、@RequestParam和@PathVariable的区别
一、注解之间的区别
@RequestParam 和 @PathVariable 一样,都是用于从request请求中绑定参数的,区别在于:
1. @RequsetParam是用于接收URL的查询串中的相应参数及请求体中的参数;
2. @PathVariable 是用于接收URL中占位符的参数
@RequestBody和 @RequestParam区别在于:
1. @RequestBody是用于接收post请求中form表单中的数据;
2. @RequsetParam是用于接收URL的查询串中的相应参数及请求体中的参数;
二、注解示例
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方法的相应形参中
@Controller
@RequestMapping("receive")
public class receiveTest {
@RequestMapping("/receiveFile")
@ResponseBody
public String receiveFile(@RequestParam(required = false, value = "file2") MultipartFile File2,
@RequestParam String FirstName, @RequestParam String LastName) {
System.out.println("FirstName : " + FirstName);
System.out.println("LastName : " + LastName);
return "Success";
}
}
2.@PathVariable 示例
现有Controller如下,当访问URL为 localhost:8080/demo2/Bob/12
时,将会把URL占位符的的参数按名绑定到demo2方法的相应形参上
@RequestMapping(value="/demo2/{name}/{id}")
public void demo2(@PathVariable String name, @PathVaribale int id){
...
}
3.@RequestBody示例
在post请求中,当访问URL为 localhost:8080/getproduct
,而且post的部分数据为{id:32}
@RequestMapping("/getproduct")
public Product getProduct(@RequestBody Product product){
...//Product包含有一个 名字为 id的属性
}