這篇文章主要介紹SpringMVC如何實現JSON數據交互及RESTful支持,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
JSON概述
JSON(JavaScript Object Notation,JS對象標記)是一種輕量級的數據交換格式,最近幾年才流行起來。JSON是基于JavaScript的一個子集,使用了C、C++、C#、Java、 JavaScript、Per、 Python等其他語言的約定,采用完全獨立于編程語言的文本格式來存儲和表示數據。這些特性使JSON成為理想的數據交互語言,它易于閱讀和編寫,同時也易于機器解析和生成。
與XML一樣,JSON也是基于純文本的數據格式。初學者可以使用JSON傳輸一個簡單的String、 Number、 Boolean,也可以傳輸一個數組或者一個復雜的 Object對象。
JSON有如下兩種數據結構。
1.對象結構
對象結構以“{”開始,以“}”結束。中間部分由0個或多個以英文“,”分隔的“key:value”對構成,其中key和value之間也是英語“:”。
{ keyl: valuel, key2: value2, …… }
2.數組結構
數組結構以“[”開始,以“]”結束。中間部分由0個或多個以英文“,”分隔的值的列表組成。
[ valuel, value2, …… ]
JSON數據轉換
為了實現瀏覽器與控制器類(Controller)之間的數據交互,Spring提供了一個HttpMessageConverter接口來完成此項工作。該接口主要用于將請求信息中的數據轉換為一個類型為T的對象,并將類型為T的對象綁定到請求方法的參數中,或者將對象轉換為響應信息傳遞給瀏覽器顯示。
Spring為 HttpMessageConverter接口提供了很多實現類,這些實現類可以對不同類型的數據進行信息轉換。其中 MappingJacksona2HttpMessageConverter是 Spring MVC默認處理JSON格式請求響應的實現類。該實現類利用 Jackson開源包讀寫JSON數據,將Java對象轉換為JSON對象和XML文檔,同時也可以將JSON對象和XML文檔轉換為Java對象。
要使用MappingJacksona2HttpMessageConverter對數據進行轉換,就需要使用 Jackson
的開源包,開發時所需的開源包及其描述如下所示。
在使用注解式開發時,需要用到兩個重要的JSON格式轉換注解@RequestBody和@ ResponseBody,
springmvc-config. 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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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.ssm.controller" /> <!-- 配置注解驅動 --> <mvc:annotation-driven /> <!-- 配置靜態資源的訪問映射,此配置中的文件,將不被前端控制器攔截 --> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <!-- 定義視圖解析器 --> <bean id="viewResoler" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 設置前綴 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 設置后綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
不僅配置了組件掃描器和視圖解析器,還配置了 Spring MVC的注解驅動<mvc: annotation- driven/>和靜態資源訪問映射mvc:resources…/。其中<mvc: annotation- driven/>配置會自動注冊 RequestMappingHandlerMapping和 RequestMappingHandlerAdapter兩個Bean,并提供對讀寫XML和讀寫JSON等功能的支持。mvc:resources…/元素用于配置靜態資源的訪問路徑。由于在web.xml中配置的“/”會將頁面中引入的靜態文件也進行攔截,而攔截后頁面中將找不到這些靜態資源文件,這樣就會引起頁面報錯。而增加了靜態資源的訪問映射配置后,程序會自動地去配置路徑下找靜態的內容。
json.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>測試JSON交互</title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"> </script> <script type="text/javascript"> function testJson(){ //獲取輸入的客戶信息 var loginname=$("#loginname").val(); var password=$("#password").val(); $.ajax({ url:"${pageContext.request.contextPath}/testJson", type:"post", //data表示發送的數據 data:JSON.stringfy({loginname:loginname,password:password}), // 定義發送請求的數據格式為JSON字符串 contentType:"application/json;charset=UTF-8", //定義回調響應的數據格式為JSON字符串,該屬性可以省略 dataType:"json", //成功響應的結果 success:function(data){ if(data!=null){ alert("您輸入的登錄名為:"+data.loginname+"密碼為:"+data.password); } } }); } </script> </head> <body> <form> 登錄名:<input type="text" name="loginname" id="loginname" /> <br /> 密碼:<input type="password" name="password" id="password" /> <br /> <input type="button" value="測試JSON交互" onclick="testJson()" /> </form> </body> </html>
在AJAX中包含了3個特別重要的屬性,其說明如下。
CustomerController.java:
package com.ssm.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import com.ssm.po.Customer; @Controller public class CustomerController { /* * 接收頁面請求的JSON數據,并返回JSON格式結果 */ @ResponseBody public Customer testJson(@RequestBody Customer customer){ //打印接收到的JSON格式數據 System.out.println(customer); return customer; } }
RESTful支持
RESTful也稱之為REST(Representational State Transfer),可以將它理解為一種軟件架構風格或設計風格。
RESTful風格就是把請求參數變成請求路徑的一種風格。例如,傳統的URL請求格式為:
http://.../queryitems?id=1
而采用RESTful風格后,其∪RL請求為:
http://.../items/1
/* * 接收RESTful風格的請求,其接收方式為GET */ @RequestMapping(value="/customer/{id}",method=RequestMethod.GET) @ResponseBody public Customer selectCustomer(@PathVariable("id") Integer id){ //查看接收數據 System.out.println(id); Customer customer=new Customer(); //模擬根據id查詢出客戶對象數據 if(id==10){ customer.setLoginname("wujit"); } //返回JSON格式的數據 return customer; }
@RequestMapping(vaue="customer/{id}", method= RequestMethod.GET)注解用于匹配請求路徑(包括參數)和方式。其中vaue="/user/{id}"表示可以匹配以“/user/{id}”結尾的請求,id為請求中的動態參數;method= RequestMethod.GET表示只接收GET方式的請求。方法中的@ PathVariable("id")注解則用于接收并綁定請求參數,它可以將請求URL中的變量映射到方法的形參上,如果請求路徑為“/user/{id}”,即請求參數中的id和方法形參名稱id一樣,則@PathVariable后面的“("id")”可以省略。
以上是SpringMVC如何實現JSON數據交互及RESTful支持的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。