SpringMVC:HttpMessageConverter
作者:互联网
HttpMessageConverter
HttpMessageConverter报文消息转换器,将请求报文转换为java对象,或将java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody、@ResponseBody、RequestEntity、ResponseEntity
1、@RequestBody(了解)
@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequetsBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值。
<form th:action="@{/testRequestBody}" method="post">
姓名:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="提交">
</form>
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody:"+requestBody);
return "success";
}
requestBody:username=admin&password=184497
注意:
GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。
2、RequestEntity(了解)
RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息。
<form th:action="@{/testRequestEntity}" method="post">
姓名:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="testRequestEntity">
</form>
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前requestEntity表示整个报文的信息
System.out.println("请求头:"+requestEntity.getHeaders());
System.out.println("请求体:"+requestEntity.getBody());
return "success";
}
请求头:[host:"localhost:8080", connection:"keep-alive", content-length:"24", cache-control:"max-age=0", sec-ch-ua:""Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""Windows"", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9", cookie:"Idea-661643a5=a54e3feb-b38c-4150-abde-c5e9c178c5bb", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
请求体:username=ad&password=123
标签:HttpMessageConverter,请求,形参,SpringMVC,报文,RequestBody,sec 来源: https://www.cnblogs.com/amok/p/15735729.html