一、JSON概述
JSON(JavaScript Object Notation, JS 对象标记)是一种轻量级的数据交换格式。与 XML 一样,JSON 也是基于纯文本的数据格式。它有对象结构和数组结构两种数据结构。
1、对象结构
对象结构以“{”开始、以“}”结束,中间部分由 0 个或多个以英文“,”分隔的 key/value 对构成,key 和 value 之间以英文“:”分隔。对象结构的语法结构如下:
{
key1:value1,
key2:value2,
...
}其中,key 必须为 String 类型,value 可以是 String、Number、Object、Array 等数据类型。例如,一个 person 对象包含姓名、密码、年龄等信息,使用 JSON 的表示形式如下:
{
"name":"tom",
"assword":"123456",
"age":40
}
2、数据结构
数组结构以“[”开始、以“]”结束,中间部分由 0 个或多个以英文“,”分隔的值的列表组成。数组结构的语法结构如下:
{
value1,
value2,
...
}上述两种(对象、数组)数据结构也可以分别组合构成更加复杂的数据结构。例如,一个 student 对象包含 sno、sname、hobby 和 college 对象,其 JSON 的表示形式如下:
{
"sno":"202102030001",
"sname":"张三",
"hobby":["乒乓球","足球"],
"college":{
"cname":"清华大学",
"city":"北京"
}
}
JSON数据格式的在线校验网站:https://www.bejson.com/
二、JSON数据交互案例
(1)引入jar包。
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
(2)配置web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 指定Spring MVC配置文件的位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--
Servlet一般都是在第一次访问时才加载,此配置表明容器在启动时就立即加载Servlet
load-on-startup:服务器启动时创建对象,值越小优先级越高,越先创建对象
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!--
/*和/都是拦截所有请求
/*:拦截到所有的请求,包括jsp,如果不写,默认值
/:拦截除*.jsp之外的所有请求
-->
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- encoding:指定一个具体的字符集 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- forceEncoding:处理 response中的字符编码 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
(3)在webapp下创建js文件目录,并引入jquery,然后配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置注解扫描的包 -->
<context:component-scan base-package="com.yht.example1"></context:component-scan>
<!-- 配置视图解析器 :拼接页面地址 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 访问路径的前缀 -->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 文件后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 使用resources过滤掉不需要dispatcherservlet的资源(即静态资源,例如css、js、html、images)。
在使用resources时必须使用annotation-driven,否则resources元素会阻止任意控制器被调用 -->
<!-- 允许js目录下的所有文件可见 -->
<mvc:resources location="/js/" mapping="/js/**" />
</beans>
如果在后续的开发中还需要去掉dispaterServlet对img和css的拦截,则加入:
<!-- 允许css目录下的所有文件可见 --> <mvc:resources location="/css/" mapping="/css/**" /> <!-- 允许img目录下的所有文件可见 --> <mvc:resources location="/img/" mapping="/img/**" />
这里需要注意的是:js目录是在webapp下的。
(4)创建实体类User。
public class User {
private String name;
private String password;
private Integer age;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
(5)在页面 index.jsp 进行JSON 数据交互。
<%--
Created by IntelliJ IDEA.
User: com.yht
Date: 2021/2/2
Time: 20:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.5.1.js"></script>
<script>
$(function () {
$("#btn").click(function () {
var name = $("#name").val();
var password = $("#password").val();
var age = $("#age").val();
$.ajax({
//请求路径
url : "${pageContext.request.contextPath }/user/testJson",
//请求类型
type : "post",
//data表示发送的数据
data : JSON.stringify({
name : name,
password : password,
age : age,
}), //定义发送请求的数据格式为JSON字符串
contentType : "application/json;charset=utf-8",
//定义回调响应的数据格式为JSON字符串,该属性可以省略
dataType : "json",
//成功响应的结果
success : function(data) {
if (data != null) {
alert("后台返回的用户的用户名:" + data.name + ",密码:" + data.password
+ ", 年龄:" + data.age );
}
}
});
});
});
</script>
</head>
<body>
<form method="post">
姓名:<input type="text" name="name" id="name"><br>
密码:<input type="text" name="password" id="password"><br>
年龄:<input type="text" name="age" id="age"><br>
<button id="btn">提交</button>
</form>
</body>
</html>
(6)创建处理请求的方法。
/**
* 接收页面请求的JSON参数,并返回JSON格式的结果
*/
@RequestMapping("/testJson")
@ResponseBody
public User testJson(@RequestBody User user) {
// 打印接收的JSON格式数据
System.out.println("接收到的User : " + user);
// 返回JSON格式的响应
return user;
}
方法中的 @RequestBody 注解用于将前端请求体中的 JSON 格式数据绑定到形参 user 上,@ResponseBody 注解用于直接返回 Person 对象(当返回 POJO 对象时默认转换为 JSON 格式数据进行响应)。
(7)测试程序