json資料格式在接口調用中、html頁面中比較常用,json格式比較簡單,解析也比較友善,是以使用很普遍。在SpringMVC中,也支援對json資料的解析和轉換,這篇文章主要總結一下在SpringMVC中如何和前台互動json資料。
本節案例是在上一章案例的基礎上做的。
jar包
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLyMTN4ETOzcTM4ETMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
本章使用jauery的ajax方法,不要到了導入jQuery函數庫。
因為在使用spring-mvc時已經選擇把所有路徑都過濾交給spring-mvc,是以此處要配置css和js等檔案,否則無法比對到路徑。此處案例隻用了js檔案,是以在spring-mvc.xml檔案中配置js檔案映射即可:
<!--配置資源映射-->
<mvc:resources location="/js/" mapping="/js/**"/>
@RequestBody
@RequestBody注解用于讀取http請求的内容(字元串),通過SpringMVC提供的HttpMessageConverter接口将讀到的内容轉換為json、xml等格式的資料并綁定到Controller類方法的參數上。
本案例完成@RequestBody注解實作接收http請求的json資料,将json資料轉換為java對象。
jsp:
<body>
通過Ajax發送Json字元串給伺服器:
<input type="button" value="發送" onclick="sendAjax()"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.min.js" > </script>
<script type="text/javascript">
function sendAjax(){
$.ajax({
type:"post"
,url:"${pageContext.request.contextPath}/stu/json"
,data:'{"studentId":"1","studentName":"張三","age":18}'
,contentType:"application/json;charset=utf-8"
,success:function(data){
alert(data);
}
});
}
</script>
</body>
SpringMVC和前台互動主要有兩種形式:
- 一種是傳json格式的資料過來,需要指定contextType為"application/json;charset=utf-8",然後在背景使用@RequestBody将json字元串轉成java對象
-
另一種就是在url的末尾傳普通的key/value串過來,需要指定contextType為"application/x-www-form-urlen",背景不用使用@RequestBoby轉換。
此案例就是以傳json格式的資料為例,下面完成Controller:
@RequestMapping("/json")
public void json(@RequestBody Student student){
System.out.println(student.getStudentName());
}
@ResponseBody
@ResponseBody注解用于将Controller類的方法傳回的對象,通過HttpMessageConverter接口轉換為指定格式的資料如:json、xml等,通過Response響應給用戶端。
此案例完成@ResponseBody注解實作将Controller類方法傳回對象轉換為json響應給用戶端:
修改Controller中的json方法為:
@RequestMapping("/json")
@ResponseBody
public Student json(@RequestBody Student student){
System.out.println(student.getStudentName());
return student;
}
配置json轉換器
這裡需要配置配置json轉換器。但是如果使用了<mvc:annotation-driven />注解驅動的話就不用以上的配置了。
測試即可:
響應的結果,null表示空值,這裡就傳回了原對象