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
HttpMessageConverter
要使用MappingJackson2HttpMessageConverter對數據進行轉換,就需要使用Jackson的開源包,開發時所需的開源包及其描述如下所示:
- 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風格支持,這對今后實際開發有極大的幫助。