1.JSON概述
1.1 什么是JSON
JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式。它是基于JavaScript的一个子集,使用了C、C++、C#、Java、JavaScript、Perl、Python等其他语言的约定,采用完全独立于编程语言的文本格式来存储和表示数据。
1.2 JSON的特点
- JSON与XML非常相似,都是用来存储数据的,并且都是基于纯文本的数据格式。与XML相比,JSON解析速度更快,占用空间更小,且易于阅读和编写,同时也易于机器解析和生成。
JSON有如下两种数据结构:
1.对象结构:
在对象结构以“{”开始,以“}”结束。中间部分由0个或多个以英文“,”分隔的name:value对构成(注意name和value之间以英文“:”分隔),其存储形式如下图所示。
对象结构的语法结构代码如下:
例如:一个address对象包含城市、街道、邮编等信息,使用JSON的表示形式如下:
{"city":"Beijing","street":"Xisanqi","postcode":100096}
2.数组结构:
数组结构以“[”开始,以“]”结束。中间部分由0个或多个以英文“,”分隔的值的列表组成,其存储形式如下图所示。
对象结构的语法结构代码如下:
[
value1,
value2,
...
]
例如,一个数组包含了String、Number、Boolean、null类型数据,使用JSON的表示形式如下:
["abc",12345,false,null]
对象、数组数据结构也可以分别组合构成更为复杂的数据结构。例如:一个person对象包含name、hobby和address对象,其代码表现形式如下:
{
"name": "zhangsan"
"hobby":["篮球","羽毛球","游泳"] "address":{ "city":"Beijing" "street":"Xisanqi" "postcode":100096 } }
注意:如果使用JSON存储单个数据(如“abc”),一定要使用数组的形式,不要使用Object形式,因为Object形式必须是“名称:值”的形式。
1.3. JSON数据转换
Spring提供了一个HttpMessageConverter
- jackson-annoations-2.8.8.jar:JSON转换注解包;
- jackson-core-2.8.8.jar:JSON转换核心包;
- jackson-databind-2.8.8.jar:JSON转换的数据绑定包。
在使用注解式开发时,需要用到2个重要的JSON格式转换注解,分别为 @RequestBody 和 @ResponseBody,关于这两个注解的说明如下表所示:
2.RESTful
2.1 什么是RESTful?
RESTful也称之为REST,是英文“Representational State Transfer”的简称。可以将他理解为一种软件架构风格或设计风格,而不是一个标准。
简单来说,RESTful风格就是把请求参数变成请求路径的一种风格。
传统的URL请求格式为:
http://.../queryItems?id=1 采用RESTful风格后,其URL请求为:
http://.../items/1
3.应用案例
开发工具:idea
Java环境: jdk1.8.0_121
项目目录:
jar包
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_3_1.xsd" version="3.1"> <display-name>chapter14</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc-config.xml文件
<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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!--定义组件扫描器,指定需要扫描的包--> <context:component-scan base-package="com.ma.controller"/> <!-- 配置注解驱动 --> <mvc:annotation-driven/> <!--配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 --> <mvc:resources mapping="/js/**" location="/js/"/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
User实体类
package com.ma.po;
/**
* @author mz
* @version V1.0
* @Description: 用户POJO * @create 2017-11-06 10:52 */ public class User { private String username; private String password; //省略setter和getter方法 }
在web目录下(WebContent)新建index.jsp,和restful.jsp,用于测试JSON数据交互和RESTful的使用。
<%--
Created by IntelliJ IDEA. User: Administrator Date: 2017/11/6 Time: 10:41 To change this template use File | Settings | File Templates. --%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>测试JSON交互</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"> </script> <script type="text/javascript"> function testJson() { var username = $("#username").val(); var password = $("#password").val(); $.ajax({ url : "${pageContext.request.contextPath}/testJson", type : "post", //data表示发送的数据 data : JSON.stringify({username:username,password:password}), //定义发送请求的数据格式为JSON字符串 contentType : "application/json;charset=UTF-8", //定义回调响应的数据格式为Json字符串,该属性可以省略 dataType : "json", //成功响应的结果 success : function (data) { if (data != null) { alert("你输入的用户名为:"+data.username+"密码为:"+data.password); } } }); } </script> </head> <body> <form> 用户名:<input type="text" name="username" id="username"/><br/> 密 码:<input type="password" name="password" id="password"/><br/> <input type="button" value="测试json交互" onclick="testJson()"/> </form> </body> </html>
restful.jsp
<%--
Created by IntelliJ IDEA. User: Administrator Date: 2017/11/6 Time: 11:32 To change this template use File | Settings | File Templates. --%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>RESTful测试</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"> </script> <script type="text/javascript"> function search() { var id = $("#number").val(); $.ajax({ url : "${pageContext.request.contextPath}/user/"+id, type : "GET", dataType : "json", success : function (data) { if (data.username != null){ alert("你查询的用户是:"+data.username); } else { alert("没有找到id为:"+id+"用户"); } } }); } </script> </head> <body> <form action=""> 编号:<input type="text" name="number" id="number"> <input type="button" value="搜索" onclick="search()"/> </form> </body> </html>
新建一个控制器类UserController。
package com.ma.controller;
import com.ma.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller public class UserController { /** * 接收页面请求的JSON数据,并返回JSON格式结果 * @param user * @return */ @RequestMapping("/testJson") @ResponseBody public User testJson(@RequestBody User user) { System.out.println(user); //返回JSON格式的响应 return user; } /** * 接收RESTful风格的请求,其接收方式为GET * @param id * @return */ @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) @ResponseBody public User selectUser(@PathVariable("id") String id) { //查看数据的接收 System.out.println("id="+id); User user = new User(); //模拟根据id查询出到用户对象数据 if (id.equals("1234")) { user.setUsername("tom"); } return user; } }
运行结果如下:
小结
主要总结一下Spring MVC中的JSON数据交互和对RESTful风格支持,这对今后实际开发有极大的帮助。