SpringMVC如何操作请求和响应报文的
文章目录
前言
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:
@RequestBody,@ResponseBody,RequestEntity,ResponseEntity
零、请求和响应报文小知识
# 一、@RequestBody
作用:该注解修饰的参数与请求体形成映射关系,并将请求体赋值给该形参
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("RequestBody = " + requestBody);
return "success";
}
打印内容
RequestBody = username=admin&password=123456
二、RequestEntity
作用:该注解修饰的形参与请求报文请求映射关系,并将请求报文赋值给修饰的形参,就可以获取请求报文的内容
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> request){
HttpHeaders headers = request.getHeaders();
HttpMethod method = request.getMethod();
Type type = request.getType();
URI url = request.getUrl();
String body = request.getBody();
System.out.println("header = "+ headers + "\n method = "
+ method + "\n type = " + type + "\n URI = " + url
+ "\n body = " + body);
return "success";
}
打印内容
header = [host:"localhost:8080", connection:"keep-alive", content-length:"29", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"", 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/100.0.4896.127 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/springMVC_demo5/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9", cookie:"Idea-aafc8dba=ffa8b7f0-935d-4c1b-ad7c-93ba1d53922c", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
method = POST
type = class java.lang.String
URI = http://localhost:8080/springMVC_demo5/testRequestEntity
body = username=admin&password=admin
三、 @ResponseBody(重点)
作用:将控制器方法的返回值响应到浏览器
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "<font color='red'>success</font>";
}
执行结果
原生servlet实现
@RequestMapping("/testResponseServletApi")
public String testResponseServletApi(HttpServletResponse response) throws IOException {
// 设置响应编码
response.setContentType("text/html;character=UTF-8");
response.getWriter().write("是你");
return null;
}
四、@RestController注解
该注解属于@ResponseBody和@Controller的复合注解,修饰类,为该控制器层下的每个方法添加@ResponseBody注解
五、ResponseEntity
六、 扩展知识
6.1 设置响应编码的方式
- response.setContentType(“text/html; charset=UTF-8”);
第一种不仅发送到浏览器的内容会使用UTF-8编码,而且还通知浏览器使用UTF-8编码方式进行显示。所以总能正常显示中文
即:服务端用utf编码,并且告诉浏览器用utf-8的编码显示
- response.setCharacterEncoding(“UTF-8”);
第二种仅仅是发送的浏览器的内容是UTF-8编码的,至于浏览器是用哪种编码方式显示不管。 所以当浏览器的显示编码方式不是UTF-8的时候,就会看到乱码,需要手动再进行一次设置。
6.2 SpringMVC处理json
- 导入jackson的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
- 开启springMVC注解驱动
在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串
<mvc:annotation-driven />
返回的java对象则自动会转为json对象
@RequestMapping("/testResponseUser")
public User testResponseUser(User user){
User user1 = new User("张三", "123456");
return user1;
}
打印内容
{"name":"张三","password":"123456"}
6.3 SpringMVC处理ajax
- 请求超链接:
<div id="app">
<a th:href="@{/testAjax}" @click="testAjax">testAjax</a><br>
</div>
- 通过vue和axios处理点击事件:
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">
var vue = new Vue({
el:"#app",
methods:{
testAjax:function (event) {
axios({
method:"post",
url:event.target.href,
params:{
username:"admin",
password:"123456"
}
}).then(function (response) {
alert(response.data);
});
event.preventDefault();
}
}
});
</script>
- 控制器方法:
@RequestMapping("/testAjax")
@ResponseBody
public String testAjax(String username, String password){
System.out.println("username:"+username+",password:"+password);
return "hello,ajax";
}
打印内容
username = admin password = 123456
总结
好好努力,加油陌生人!!!