target
掌握 Json是什么
掌握Json的两种表现形式
掌握 在SpringMVC中如何处理Json数据
切记:SpringMVC中使用Json需要Jackson包的支持
Spring MVC 在数据绑定的过程中需要对传递数据的格式和类型进行转换,它既可以转换 String 等类型的数据,也可以转换 JSON 等其他类型的数据。本节将针对 SpringMVC 中 JSON 类型的数据交互进行讲解。
1. JSON 概述
JSON(JavaScript Object Notation, JS 对象标记)是一种轻量级的数据交换格式。
JSON是Douglas Crockford在2001年开始推广使用的数据格式,在2005年-2006年正式成为主流的数据格式,雅虎和谷歌就在那时候开始广泛地使用JSON格式。
与 XML 一样,JSON 也是基于纯文本的数据格式。它有对象结构和数组结构两种数据结构。
1.1 对象结构
对象结构以{开始、以}结束,中间部分由 0 个或多个以英文,分隔的 key/value 对构成,key 和 value 之间以英文:分隔。对象结构的语法结构如下:
{
key1:value1,
key2:value2,
...
}
其中,key 必须为 String 类型,value 可以是 String、Number、Object、Array 等数据类型。例如,一个 person 对象包含姓名、密码、年龄等信息,使用 JSON 的表示形式如下:
{
"pname":"张三",
"password":"123456",
"page":40
}
1.2 数组结构
数组结构以[开始、以]结束,中间部分由 0 个或多个以英文,分隔的值的列表组成。数组结构的语法结构如下:
[
value1,
value2,
...
]
上述两种(对象、数组)数据结构也可以分别组合构成更加复杂的数据结构。例如,一个 student 对象包含 sno、sname、hobby 和 college 对象,其 JSON 的表示形式如下:
{
"sno":"201802228888",
"sname":"张三",
"hobby":["篮球","足球"],
"college":{
"cname":"清华大学",
"city":"北京"
}
}
2. JSON 数据转换
为实现浏览器与控制器类之间的 JSON 数据交互,Spring MVC 提供了 MappingJackson2HttpMessageConverter 实现类默认处理 JSON 格式请求响应。该实现类利用 Jackson 开源包读写 JSON 数据,将 Java 对象转换为 JSON 对象和 XML 文档,同时也可以将 JSON 对象和 XML 文档转换为 Java 对象。
在使用注解开发时需要用到两个重要的 JSON 格式转换注解,分别是 @RequestBody 和 @ResponseBody。
@RequestBody:用于将请求体中的数据绑定到方法的形参中,该注解应用在方法的形参上。
@ResponseBody:用于直接返回 return 对象,该注解应用在方法上。
下面通过一个案例来演示如何进行 JSON 数据交互,具体步骤如下。
创建 动态 Web项目:SpringMVC-09
① 导入 jar
将以下jar 复制到 lib 目录下:
commons-logging-1.2.jar
jackson-annotations-2.10.1.jar
jackson-core-2.10.1.jar
jackson-databind-2.10.1.jar
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
spring-web-4.3.9.RELEASE.jar
spring-webmvc-4.3.9.RELEASE.jar
注意:需要Jackson的包支持
② 配置 web.xml
web.xml 文件中对 Spring MVC 的前端控制器等信息进行配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVC-09</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The front controller of this Spring Web application, responsible for
handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
③ 配置 Spring MVC 的核心配置文件
在 src 下创建 Spring MVC 的核心配置文件 springmvc.xml,代码如下:
<?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"
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">
<!-- 使用扫描机制扫描控制器类 -->
<context:component-scan base-package="com.lee.spring.controller" />
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
④ 创建 POJO 类
package com.lee.spring.bean;
public class Person {
private String pname;
private String password;
private Integer page;
// getter、setter略
@Override
public String toString() {
return "Person [pname=" + pname + ", password=" + password + ", page=" + page + "]";
}
}
⑤ 创建 JSP页面测试 JSON 数据交互
在页面 index.jsp 来测试 JSON 数据交互,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javaScript" src="${pageContext.request.contextPath }/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<form action="" id="form1">
用户名:<input type="text" name="pname" id="pname" /><br>
密码:<input type="password" name="password" id="password" /> <br>
年龄:<input type="text" name="page" id="page"><br>
<input type="button" value="测试" onclick="testJson()" />
</form>
<script type="text/javaScript">
function testJson() {
$.ajax({
//请求路径
url : "${pageContext.request.contextPath }/testJson",
//请求类型
type : "post",
//data表示发送的数据
data : $('#form1').serialize(), //将表单数据格式为JSON字符串
dataType : "json",
//成功响应的结果
success : function(data) {
if (data != null) {
alert("输入的用户名:" + data.pname + ",密码:" + data.password + ", 年龄:" + data.page);
}
}
});
}
</script>
</body>
</html>
在 index.jsp 页面中编写了一个测试 JSON 交互的表单,当单击"测试"按钮时执行页面中的 testJson() 函数。在该函数中使用了 jQuery 的 AJAX 方式将 JSON 格式的数据传递给以“/testJson”结尾的请求中。
因为在 index.jsp 中使用的是 jQuery 的 AJAX 进行的 JSON 数据提交和响应,所以还需要引入 jquery.js 文件。本例引入了 WebContent 目录下 js 文件夹中的 jquery-3.4.1.min.js。
⑥ 创建控制器类
创建一个用于用户操作的控制器类 TestController,代码如下:
package com.lee.spring.controller;
@Controller
public class TestController {
/**
* 接收页面请求的JSON参数,并返回JSON格式的结果
*/
@RequestMapping("testJson")
@ResponseBody
public Person testJson( Person user) {
// 打印接收的JSON格式数据
System.out.println(user);
// 返回JSON格式的响应
return user;
}
}
在上述控制器类中编写了接收和响应 JSON 格式数据的 testJson 方法,@ResponseBody 注解用于直接返回 Person 对象(当返回 POJO 对象时默认转换为 JSON 格式数据进行响应)。
⑦ 运行 index.jsp 页面,测试程序
将应用发布到 Tomcat 服务器并启动服务器,在浏览器中访问地址"http://localhost:8080/SpringMVC-09/",运行结果如下:

输入框中输入信息后单击“测试”按钮,当程序正确执行时页面将弹出显示输入信息的对话框,如图所示:

同时,Eclipse 的控制台将打印出相应数据:
Person [pname=张三, password=123456, page=12]
切记:SpringMVC中使用 @ResponseBody 需要 Jackson包的支持。