1. 程式人生 > 程式設計 >SpringMVC JSON資料互動及RESTful支援實現方法

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
的開源包,開發時所需的開源包及其描述如下所示。

  • jackson-annoations-2.8. 8. Jar:JSON轉換註解包。
  • jackson-core-2.8. 8.jar:JSON轉換核心包。
  • Jackson- databind-2.8.8.jar:JSON轉換的資料繫結包。

在使用註解式開發時,需要用到兩個重要的JSON格式轉換註解@RequestBody和@ ResponseBody,

SpringMVC JSON資料互動及RESTful支援實現方法
SpringMVC JSON資料互動及RESTful支援實現方法

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個特別重要的屬性,其說明如下。

  • data:即請求時攜帶的資料,當使用JSON格式時,要注意編寫規範。
  • contentType:當請求資料為JSON格式時,值必須為 application/json。
  • dataType:當響應資料為JSON時,可以定義dataType屬性,並且值必須為json。其中
  • dataType:"json"也可以省略不寫,頁面會自動識別響應的資料格式。
  • 在上述測試頁面 json.jsp還需要引入jquery.js檔案,本例中引入了 WebContent目錄下js資料夾中的jquery-1.11.3.min.js。

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")”可以省略。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。