SpringMVC詳解(六)------與json互動
Json(JavaScript Object Notation),它是一種輕量級資料交換格式,格式簡單,易于讀寫,目前使用特别廣泛。那麼這篇部落格我們主要談談在 SpringMVC 中,如何對 json 資料格式進行解析和轉換?
本篇部落格源碼連結:http://pan.baidu.com/s/1kURnwDx 密碼:b37t
1、兩種互動模式

上圖顯示了用戶端請求資料的兩種格式,一種是 直接請求 json 資料,另一種是 key/value 資料。但是不管請求是哪種資料,為了在前端頁面友善對結果進行解析。最終我們都轉換為 json 資料格式。
2、導入相應的 jar 包(詳情參看源碼)
3、在 springmvc.xml 檔案中配置 json 轉換器
第一種方法:
<mvc:annotation-driven ></mvc:annotation-driven>
第二種方法:
<!-- 用于将對象轉換為 JSON -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
4、請求為 json 資料測試
這裡我們需要注意兩個注解:
@ResponseBody把背景pojo轉換json對象,傳回到頁面。
@RequestBody接受前台json資料,把json資料自動封裝pojo。
①、jsp 頁面
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SpringMVC和 json 互動</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js" ></script>
</head>
<script type="text/javascript">
var dataJson = {
'username':'Bob',
'sex':'男'
};
function requestJson(){
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/requestJson",
//指定資料格式為 json
contentType:"application/json;charset=UTF-8",
data:JSON.stringify(dataJson),
dataType:"json",
success:function(data){
console.log(data.username);
console.log(data.sex);
}
});
}
</script>
<body>
<button onclick="requestJson()" value="請求是json,傳回json">請求是json,傳回json</button>
</body>
</html>
②、Controller
package com.ys.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ys.po.User;
@Controller
public class UserController {
//請求為json,傳回json
@RequestMapping("/requestJson")
//@RequestBody将請求資訊的json串轉成user對象
//@ResponseBody将user對象轉成json輸出
@ResponseBody
public User requestJson(@RequestBody User user) throws Exception{
System.out.println(user);
return user;//由于@ResponseBody注解,将user轉成json格式傳回
}
}
③、測試
我們通路上面的jsp頁面,然後點選按鈕,進入到 Controller
然後我們檢視傳回的資料:
5、請求為 key/value 資料測試
①、JSP 頁面
②、Controller
//請求為key/value,傳回json
@RequestMapping("/requestKeyValue")
//@RequestBody将請求資訊的json串轉成user對象
@ResponseBody
public User requestKeyValue(User user) throws Exception{
System.out.println(user);
return user;
}
然後傳回資料:
6、遇到的問題
①、如下代碼,由于我們使用 Ajax 送出,我們在 JSP 頁面引入了jquery 檔案,發現無論使用絕對路徑還是相對路徑,系統總是找不到這個檔案?
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js" ></script>
原因:因為你在web.xml 檔案中,對于過濾器的配置是攔截所有請求。是以類似于*.js,或者*.css這樣的檔案也被攔截了,故通路不到。
解決辦法:
第一種辦法:我們可以使用上面配置的攔截器隻攔截 *.do,或者*.action,而不是 “/”。那麼SpringMVC容器将不會攔截*.js,*.css這樣的檔案。但是這種風格不支援 Restful,建議不采用。
第二種方法:在web.xml中配置攔截器的過濾請求
<!--要寫在DispatcherServlet的前面, 讓 defaultServlet先攔截請求,這樣請求就不會進入Spring了,我想性能是最好的吧。-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
第三種方法:在spingmvc.xml 中配置對靜态資源不過濾
<!-- 配置靜态檔案過濾器 -->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
②、也是比較容易犯的錯誤 415
這個錯誤産生的原因有很多。我們需要一步一步的排查:
第一步:必須保證導入的 jackson相關的jar包是全的。
第二步:在springmvc.xml檔案中的配置的json轉換器一定不能缺少,如何配檢視本篇部落格的第三點
第三步:書寫 Ajax 請求時。contentType:"application/json;charset=UTF-8",不要不寫 contentType 這個屬性
第四步:Ajax傳給背景的不要直接傳字元串,要轉換成json,即 data:JSON.stringify(dataJson),
作者:IT可樂
出處:http://www.cnblogs.com/ysocean/
資源:微信搜【IT可樂】關注我,回複 【電子書】有我特别篩選的免費電子書。
本文版權歸作者所有,歡迎轉載,但未經作者同意不能轉載,否則保留追究法律責任的權利。