3.14 @ResponseBody注解 示例 @ResponseBody返回JSON格式的数据

3.14 @ResponseBody注解

用途

org.springframework.web.bind.annotation.ResponseBody注解用于Controller的请求处理方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区

适用范围

当返回的数据不是HTML标签的页面,而是其他某种格式的数据时(如JSONXML等)使用它

示例 @ResponseBody返回JSON格式的数据

创建一个ResponseBodyTest项目,在WebContent目录下创建一个js目录,加入jQueryjson2js文件,在WEB-INF/lib目录中加入Jacksonjar文件。

项目结构

展开/折叠
G:\Desktop\随书源码\Spring+Mybatis企业应用实战(第2版)\codes\03\ResponseBodyTest
├─src\
│ └─org\
│   └─fkit\
│     ├─controller\
│     │ └─BookController.java
│     └─domain\
│       └─Book.java
└─WebContent\
  ├─index.jsp
  ├─js\
  │ ├─jquery-1.11.0.min.js
  │ ├─jquery-migrate-1.2.1.min.js
  │ └─json2.js
  ├─META-INF\
  │ └─MANIFEST.MF
  └─WEB-INF\
    ├─lib\
    │ ├─commons-logging-1.2.jar
    │ ├─jackson-annotations-2.9.2.jar
    │ ├─jackson-core-2.9.2.jar
    │ ├─jackson-databind-2.9.2.jar
    │ ├─spring-aop-5.0.1.RELEASE.jar
    │ ├─spring-aspects-5.0.1.RELEASE.jar
    │ ├─spring-beans-5.0.1.RELEASE.jar
    │ ├─spring-context-5.0.1.RELEASE.jar
    │ ├─spring-context-indexer-5.0.1.RELEASE.jar
    │ ├─spring-context-support-5.0.1.RELEASE.jar
    │ ├─spring-core-5.0.1.RELEASE.jar
    │ ├─spring-expression-5.0.1.RELEASE.jar
    │ ├─spring-instrument-5.0.1.RELEASE.jar
    │ ├─spring-jcl-5.0.1.RELEASE.jar
    │ ├─spring-jdbc-5.0.1.RELEASE.jar
    │ ├─spring-jms-5.0.1.RELEASE.jar
    │ ├─spring-messaging-5.0.1.RELEASE.jar
    │ ├─spring-orm-5.0.1.RELEASE.jar
    │ ├─spring-oxm-5.0.1.RELEASE.jar
    │ ├─spring-test-5.0.1.RELEASE.jar
    │ ├─spring-tx-5.0.1.RELEASE.jar
    │ ├─spring-web-5.0.1.RELEASE.jar
    │ ├─spring-webflux-5.0.1.RELEASE.jar
    │ ├─spring-webmvc-5.0.1.RELEASE.jar
    │ └─spring-websocket-5.0.1.RELEASE.jar
    ├─springmvc-config.xml
    └─web.xml

BookController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package org.fkit.controller;

import java.util.ArrayList;
import java.util.List;
import org.fkit.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/json")
public class BookController
{
@RequestMapping(value = "/testRequestBody")
// @ResponseBody注解会自动将集合数据转换json格式并返回给客户端.
@ResponseBody
public Object getJson()
{
List<Book> list = new ArrayList<Book>();
list.add(new Book(1, "书名字1", "作者1"));
list.add(new Book(2, "书名字2", "作者2"));
return list;
}
}

getJson方法会将List集合数据转换成JSON格式,然后将其返回到客户端。

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试返回JSON格式的数据</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
testResponseBody();
});
function testResponseBody() {
//提交post请求
$.post("${pageContext.request.contextPath}/json/testRequestBody", null,
//请求成功后调用
function(data) {
$.each(data, function() {
//把获取到的数据封装成表格的一行
var tr = $("<tr align='center'/>");
$("<td/>").html(this.id).appendTo(tr);
$("<td/>").html(this.name).appendTo(tr);
$("<td/>").html(this.author).appendTo(tr);
//把这行追加到表格之中
$("#booktable").append(tr);
})
},
//表示请求的是json数据
"json");
}
</script>
</head>
<body>
<table id="booktable" border="1" style="border-collapse: collapse;">
<tr align="center">
<th>编号</th>
<th>书名</th>
<th>作者</th>
</tr>
</table>
</body>
</html>

分析

index.jsp页面代码分析如下:
(1)页面使用jQuery发送请求,在页面的<head>部分,引入了jQueryjson2的js文件。
(2)载入页面时调用testResponseBody函数。
(3) testResponseBody函数发送异步请求到"json/testRequestBody",请求成功将返回一个JSON数据,该数据包含多个书籍信息。接到返回的数据后使用jQuery将数据设置到页面的<table>表单中。

测试

部署ResponseBodyTest这个Web应用,在浏览器中输入如下URL来测试应用:

1
http://localhost:8080/ResponseBodyTest/

载入index.jsp页面时会发送Ajax请求, getJson方法创建多个Book对象并将其封装到List集合中返回,方法上的@ResponseBody注解会将集合数据转换为JSON格式数据并将其返回客户端。
此时客户端显示内容如下:

1
2
3
编号     书名     作者
1 书名字1 作者1
2 书名字2 作者2

这表示Spring MVC成功将包含Book对象的集合数据被转换成JSON格式并被成功写回客户端。