目录
@RequestBody
注解@RequestBody接收的参数是来自请求体中的,一般用于处理非Content-Type:application/x-www-form-urlencoded
编码格式的数据,一般用于处理:application/json、application/xml等类型数据
像我们做的项目,如果说是application/json类型的数据,我们是用@RequestBody就可以将body中的所受json数据传给后端控制器,进行解析;
对于Get、POST请求,因为@RequestBody,接收的参数是来自请求体中的,而GET请求数据是放在请求行中,所以我们@RequestBody一般对应使用的请求是POST请求,然后我们的@RequestBody解析数据;
注意,请求前后的url不改变。通过请求后的页面可知
注意:
@PostMapping("test")
public Object test(@RequestBody TestVO testVO, @RequestBody TestTwoVO testTwoVO) {
System.out.println(testVO.getUsername());
System.out.println(testVO.getPassword());
System.out.println(testTwoVO.getUsernameTwo());
System.out.println(testTwoVO.getPasswordTwo());
return null;
}
WARN 26532 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
由于前端往后端传数据是以IO流的方式,而第一个@RequestBody在接收完自己的数据后,就把IO流关掉了,导致第二个@RequestBody无法再读取上一个IO流,所以@RequestBody不能在同一个方法中出现多次
总结:
如果我们contentType是:form-data、x-www-form-urlencoded这种,不能使用@RequestBody,可以使用RequestParam——>因为这两种没有json字符串部分;
@RequestParam
使用application/json时候,json字符串是不可用的,url后的?后面添加参数可以使用form-data,x-www-form-urlencoded,但是要将Headers里的Content-Type删掉
(@RequestParam Map map)
在url中的?后面添加参数即可使
另外,使用@RequestParam:要指明前端传过来的参数名并与其对应
@PostMapping("test")
public Object test(@RequestParam (value = "username") String username,
@RequestParam (value = "password") String password){
System.out.println(username);
System.out.println(password);
return null;
}
get、post请求
(16条消息) http请求,get请求和post请求体以及响应体_紫枫叶520的博客-CSDN博客_请求体
@PathVariable
@PathVariable的作用是获取URL的动态参数,尝尝用于RestFul风格的编程
例如:通过id获得用户信息,前端的url可以表示为
http://localhost:8080/getUser/1 这个1就是想要查询的用户id
后端通过@PathVariable来接收这个动态参数
@GetMapping("/getUser/{id}")
public User getUser(@PathVariable("id") String id){
return userService.getUserById(id);
}