Spring MVC如何進行JSON數據的傳輸與接受

本篇文章寫給剛接觸SpingMVC的同道中人,雖然筆者自己水平也不高,但聊勝於無吧,但願能夠給某些人帶來幫助

筆者同時再次說明,運行本例時,需注意一些配置文件和網頁腳本的路徑,由於筆者的文件路徑與讀者的未必相同

首先準備如下 jar包:
commons-logging-1.1.3.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar
spring-web-4.0.6.RELEASE.jar
spring-webmvc-4.0.6.RELEASE.jar
其中commons-logging-1.1.3.jar,jackson-core-asl-1.9.2.jar,jackson-mapper-asl-1.9.2.jar都可在struts2的工具包中取得

導入以上包後,去web.xml中進行配置,配置文件以下:javascript

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>web</display-name> <!-- 配置springMVC請求分配Servlet --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- <!-- 聲明配置文件存放位置和配置文件的名稱,加入不配置此標籤,springMVC的配置文件名稱默認爲<servlet-name>的值加上"-servlet.xml",例如本例即是springMVC-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/*-servlet.xml</param-value> </init-param> --> <!-- 值小於1時,表示容器啓動時並不加載此servlet,此時只有當第一次使用servlet時纔會加載,但當值大於等於1時,表示容器啓動時會當即加載此servlet,此時值越大表示加載的優先級越小 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 請求連接以do結尾,具體怎麼回事請耐心繼續往下看 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>

接下來咱們再看springMVC-servlet.xml,以下:html

<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 掃描指定包下的全部類,假若發現@Component,@Controller,@Service,@Repsitory等註解,則將相應的類實例化 --> <context:component-scan base-package="org.xt.controller"/> <!-- 配置視圖資源 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 此乃視圖資源的前綴 --> <property name="prefix" value="/WEB-INF/page"/> <!-- 此乃視圖資源的後綴 --> <property name="suffix" value=".jsp"/> </bean> <!-- 此處乃進行json數據傳輸的關鍵,當配置 --> <bean id="jsonMapping" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonMapping"/> </list> </property> </bean> </beans>

接下來咱們再看vo對象即值對象User.java,以下:java

package org.xt.pojo; import java.io.Serializable; @SuppressWarnings("serial") public class User implements Serializable { private long userId; private String userName; private String userPassword; public long getUserId() { return this.userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return this.userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } }

好接下來便輪到了Controller的類TestJSONController.java,以下:jquery

package org.xt.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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.xt.pojo.User; @Controller @RequestMapping("/test") public class TestJSONController { /* *看value屬性,是以do結尾的,這正是web.xml配置url-pattern的值爲*.do的緣由, *這樣全部的請求連接都必須以.do結尾,這樣作的好處在於能夠將請求連接同其餘連接區分開來. *筆者建議如此作(固然了,你也能夠將.do換成.html,.htm或者其餘) */ @RequestMapping(value = "/testJSON.do",method={RequestMethod.POST}) @ResponseBody public User testJSON(@RequestBody User user) { System.out.println(user.getUserName() + " " + user.getUserPassword()); return user; } }

在以上類中出現的@ResponseBody和@RequestBody是關鍵,前者用於將JSON數據返回客戶端,後者用於接受客戶端的JSON數據web

 

接下來咱們來看看客戶端的代碼,客戶端的代碼由jquery完成ajax

<%@ 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>TestJSONForSpringMVC</title> </head> <body> 用戶名: <input id="userName" type="text" style="width:150px" /> <br /> <br />&nbsp;&nbsp;&nbsp;&nbsp;碼: <input id="userPassword" type="password" style="width:150px" /> <br /> <br /> <input id="login" type="button" value="登陸" /> <!-- 注意了,此處jquery的路徑記得替換成你本身jquery所在的路徑 --> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $("#login").click(function() { $.ajax({ url : "test/testJSON.do", type : "POST", dataType : "json", contentType : "application/json;charset=UTF-8", data : JSON.stringify({ userId : "1", userName : $("#userName").val(), userPassword : $("#userPassword").val() }), success : function(result) { alert(JSON.stringify(result)); }, error:function(result){ alert("Sorry,you are make a error!"); } }); }); </script> </body> </html>

以上jsp文件中出現了一個JSON.stringify()函數,此函數由jquery提供,做用在於將JSON數據轉換爲字符串,之因此要這麼作,緣由在於服務端的@RequestBody只能識別字符串,而不能識別JSON對象spring

 

--寫於2014-09-10 夜express

相關文章
相關標籤/搜索