目录
3、通过 HttpServletResponse 响应浏览器数据
这次笔记使用的模块是 SpringMVC-demo4
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponseEntity
1、@ReqyuestBody
@RequestBody可以获取请求体,将请求报文转换为Java对象,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值
① 在 src/main/webapp/WEB-INF 下创建首页 index.html,存放测试的表单
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<!-- 测试@RequestBody注解 -->
<form th:action="@{/testRequestBody}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="测试@RequestBody"><br>
</form>
</body>
</html>
② 在 HttpController 控制器类中添加方法
// 测试@RequestBody注解
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody:"+requestBody);
return "success";
}
③ 创建跳转成功标志页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
success
</body>
</html>
④ 运行测试,控制台输出如下
2、RequestEntity
RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders() 获取请求头信息,通过 getBody() 获取请求体信息
① 在 index.html 添加测试的表单
<!-- 测试RequestEntity类型 -->
<form th:action="@{/testRequestBody}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="测试RequestEntity"><br>
</form>
② 在 HttpController 控制器类添加控制器方法
// 测试RequestEntity类型
@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:"30", cache-control:"max-age=0", origin:"http://localhost:8080", upgrade-insecure-requests:"1", user-agent:"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3883.400 QQBrowser/10.8.4559.400", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", referer:"http://localhost:8080/SpringMVC_demo4/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9", cookie:"Idea-c7c6cd52=0fa0e2dd-98cb-4e84-89af-685388373edb", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
请求体: username=admin&password=123456
3、通过 HttpServletResponse 响应浏览器数据
① 在 HttpController 类中添加控制器方法
// 测试通过 HttpServletResponse 响应浏览器数据
// 若不需要实现页面跳转,可以设置为void或return null
@RequestMapping("/testResponse")
public void testResponse(HttpServletResponse response) throws IOException {
//这里可以使用response.getWriter().write(),也可以使用println。
//使用writer()要以流的方式传输,println可以用object类型
response.setContentType("text/html;charset=UTF-8"); //解决中文乱码
response.getWriter().println("hello,帅哥");
}
② 在 index.html 页面添加测试的链接
<!-- 测试通过 HttpServletResponse 响应浏览器数据 -->
<a th:href="@{/testResponse}">通过HttpServletResponse响应浏览器数据</a>
③ 运行测试,结果在浏览器页面显示如下
4、@ResponseBody
@ResponseBody 用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
① 在 HttpController 类中添加方法
// 测试@ResponseBody注解
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "success";
}
② 修改 success.html 页面,以便之后的测试能比较明显
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
③ 运行测试,浏览器显示如下
④ 将以上方法的 @ResponseBody 注解注释掉,这时返回值 success 会被视图解析器解析
// 测试@ResponseBody注解
@RequestMapping("/testResponseBody")
//@ResponseBody
public String testResponseBody(){
return "success";
}
⑤ 运行测试,浏览器显示如下
5、SpringMVC处理json
首先先验证一下如果使用 @ResponseBody 注解标识的方法返回一个java对象,浏览器能否识别接收
① 在 bean 目录下创建 User 类,属性如下,创建构造方法、set和get方法、toString方法
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
② 在 HttpController 下创建方法
// 测试通过@Response响应浏览器数据User对象
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"张三","123456",20,"男");
}
③ 在 index.html 添加测试的超链接
<!-- 测试通过@Response响应浏览器数据User对象 -->
<a th:href="@{/testResponseUser}">测试通过@Response响应浏览器数据User对象</a><br>
④ 运行测试,浏览器报错500
接下来讲SpringMVC处理json
① 首先要在 pom.xml 中导入 jackson 的依赖
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
② 在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串
<mvc:annotation-driven />
③ 在处理器方法上使用@ResponseBody注解进行标识
④ 将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串 (与上面验证的方法一样)
// 测试通过@Response响应浏览器数据User对象
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"张三","123456",20,"男");
}
⑤ 重新部署项目,打开上面验证的测试链接,发现浏览器可以识别 User 对象了,如下图
根据其内容被 { } 包围,可以判断这是一个 json 对象
6、SpringMVC处理ajax
① 在 src/main/webapp/static/js 目录下移入 axios.min.js 和 vue.js
② 在 HttpController 类中添加方法
// 测试SpringMVC处理ajax
@RequestMapping("/testAxios")
@ResponseBody
public String testAxios(String username, String password){
System.out.println("username = " + username + ", password = " + password);
return "hello,axios";
}
③ 在 index.html 添加测试的链接,并绑定单击事件
<!-- 测试SpringMVC处理ajax -->
<div id="app">
<a @click="textAxios" th:href="@{/testAxios}">SpringMVC处理ajax</a>
</div>
<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">
new Vue({
el:"#app",
method:{
// event 表示当前的事件
textAxios:function (event){
axios({
method:"post",
url:event.target.href,
params:{
username:"admin",
password:"123456"
}
}).then(function (response){ //response表示当前响应的数据
alert(response.data);
});
event.preventDefault(); //取消当前事件的默认行为,这里就是超链接行为
}
}
});
</script>
④ 由于引入了 axios.min.js 和 vue.js,此时的 target 中没有这两个东西,需要重新 package,服务器才会有这两样
⑤ 运行测试,页面弹窗如下
控制台输出如下
7、@RestController 注解
@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解
8、ResponseEntity
ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文