示例 @RequestBody接收JSON格式的数据

示例 @RequestBody接收JSON格式的数据

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

项目结构

展开/折叠
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
44
45
46
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

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<%@ 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">
// DOM加载完毕后就直接发送请求
$(document).ready(function() {
testRequestBody();
});
function testRequestBody() {
//发送ajax请求
$.ajax(// 发送请求的URL字符串。
"${pageContext.request.contextPath}/json/testRequestBody", {
// 预期服务器返回的数据类型。
dataType : "json",
// 请求方式 POST或GET
type : "post",
// 发送信息至服务器时的内容编码类型
contentType : "application/json",
// 发送到服务器的数据。
data : JSON.stringify({
id : 1,
name : "一本书的名字"
}),
// 默认设置为true,此时所有请求均为异步请求。
// 如果设置为false,则发送同步请求
async : true,
// 请求成功后的回调函数。
success : function(data) {
console.log(data);
//使用接收到的数据更新网页内容
$("#id").html(data.id);
$("#name").html(data.name);
$("#author").html(data.author);
},
// 请求出错时调用的函数
error : function() {
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
编号:
<span id="id"></span>
<br> 书名:
<span id="name"></span>
<br> 作者:
<span id="author"></span>
<br>
</body>
</html>

index.jsp页面代码分析如下:
(1)页面使用jQuery发送JSON数据,在页面的<head>部分,引入了jQueryjson2js文件。
(2)页面载入时调用testRequestBody函数。
(3)testRequestBody函数的

  • 第一个参数表示要请求的URL是:"json/testRequestBody",
  • 第二个参数是这次请求相关的一些设置选项,这些选项解释如下:
    • contentType选项:contentType:"application/json",,其表示发送的内容编码格式为JSON
    • data选项:data : JSON.stringify({id : 1,name : "一本书的名字"}),表示发送一个JSON数据;
    • success选项表示:如果请求成功则将接到的JSON数据设置到页面的<span>当中

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
25
26
27
28
29
30
31
32
33
34
package org.fkit.controller;

import javax.servlet.http.HttpServletResponse;
import org.fkit.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/json")
public class BookController
{
// @RequestBody根据json数据,转换成对应的Object
@RequestMapping(value = "/testRequestBody")
// @RequestBody Book book:使用@RequestBody获取JSON数据,
// 然后将JSON数据设置到对应的Book对象的属性之中.
// 第二个参数 HttpServletResponse response用来输出响应数据到客户端
public void setJson(@RequestBody Book book, HttpServletResponse response)
throws Exception
{
// ObjectMapper类是Jackson库的主要类。
// 它提供一些功能将Java对象转换成对应的JSON格式的数据
ObjectMapper mapper = new ObjectMapper();
// 将book对象转换成json,并输出到控制台
System.out.println(mapper.writeValueAsString(book));
// 设置完整的信息
book.setAuthor("小明");
// 设置响应类型
response.setContentType("text/html;charset=UTF-8");
// 将book对象转换成json写出到客户端
response.getWriter().println(mapper.writeValueAsString(book));
}
}

setJson方法中的

  • 第一个参数@RequestBody Book book表示,使用@RequestBody注解获取JSON数据后,将JSON数据设置到对应的Book对象的属性当中。
  • 第二个参数是HttpServletResponse对象,用来输出响应数据到客户端。

向前台JSP页面的JSON数据中传入了idname,为了测试接收数据,使用System.out.println(mapper.writeValueAsString(book));代码将接收到的JSON数据中的book对象打印在控制台上。
为了测试传递数据到JSP页面,在该方法中还给book对象的author对象设置了个值,并将其写出到客户端.

Book.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package org.fkit.domain;

import java.io.Serializable;

public class Book implements Serializable
{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String author;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
@Override
public String toString()
{
return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
}
}

Book类中定义了3个属性:idnameauthor,用于接收向JSP页面传入的JSON数据toString方法用来输出获取的数据对象信息.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件, -->
<!-- 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan
base-package="org.fkit.controller" />
<!-- 默认配置方案 -->
<mvc:annotation-driven />
<!-- 静态资源处理 -->
<mvc:default-servlet-handler />
<!-- 视图解析器 p:prefix属性表示前缀 p:suffix 表示后缀 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/" p:suffix=".jsp" />
</beans>

在引入静态文件,例如jQuery.js时,需要加入<mvc:default-servlet-handler />从而使用默认的Servlet来响应静态文件。如果没有加入该配置,则执行时页面会报404错误,而控制台会提出警告:

测试

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

1
http://localhost:8080/RequestBodyTest/

载入index.jsp页面时会发送Ajax请求,并传递JSON数据, BookController接收到请求后,@RequestBody注解会将接收到的JSON数据设置到Book形式参数对应的属性当中。控制台输出如下:

1
{"id":1,"name":"一本书的名字","author":null}

可以看到,JSON数据传递的idname被赋值到Book对象的属性中。接下来, setJson方法给Book对象的author属性设置了值,并将Book对象转换成JSON写出到客户端。
此时客户端显示效果如下:

1
2
3
 编号: 1
书名: 一本书的名字
作者: 小明

这表示Spring MVC成功将Book对象被以JSON数据格式成功写到客户端了。

个人总结

使用JSON交换的步骤:

  1. 使用jQuery发送ajax请求,并将数据以JSON格式发送.
  2. 引入Jacksonjar包,使用@RequstBody接收数据,该注解可以解析请求体中的JSON数据,并设置到其后面的对象上。
  3. 使用Jackson包中的ObjectMapper对象.writeValueAsString(Java对象)方法,将Java对象转为JSON字符串.
  4. 使用HttpServletResponse写到客户端即可.
  5. 使用jQuery根据接收到的JSON数据操作DOM即可。