Spring mvc,jQuery和JSON數據交互

1、實驗環境的搭建

一、Spring mvc jar。html

導入spring mvc運行所需jar包。導入以下(有多餘)java

 

 

二、json的支持jar

 

 

 

三、加入jQuery。

選用jquery-3.0.0.min.js,放在WebRoot/JS文件夾jquery

 

 

導入jQuery到jsp頁面以下web

 

 

 

四、web.xml

<?xml version="1.0" encoding="UTF-8"?>ajax

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">spring

  <display-name>springmvcjson</display-name>json

  <servlet>瀏覽器

  <servlet-name>springmvc</servlet-name>spring-mvc

  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>mvc

  <init-param>

  <param-name>contextConfigLocation</param-name>

  <param-value>classpath:springmvc.xml</param-value>

  </init-param>

  <load-on-startup>1</load-on-startup>

  </servlet>

 

  <servlet-mapping>

  <servlet-name>springmvc</servlet-name>

  <url-pattern>*.action</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.xml

classpath下

<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

         xsi:schemaLocation="http://www.springframework.org/schema/beans

                   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

                   http://www.springframework.org/schema/mvc

                   http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd

                   http://www.springframework.org/schema/context

                   http://www.springframework.org/schema/context/spring-context-3.2.xsd

                   http://www.springframework.org/schema/aop

                   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

                   http://www.springframework.org/schema/tx

                   http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

        

         <!-- <bean name="/test01.action" class="com.xzw.json.controller.JsonTest"></bean> -->

         <!-- View -->

         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

        

        

         <!-- 註解映射和適配器 -->

         <mvc:annotation-driven ></mvc:annotation-driven>

        

  

  

         <!-- 組件掃描 -->

         <context:component-scan base-package="com.xzw.json.controller"></context:component-scan>

        

         <!-- 使用@Autowired、@Required等註解

         如沒必要設置<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>和

         <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>等等

         -->

         <context:annotation-config /> 

        

 

</beans>

 

2、實驗例子編寫

 

一、請求和返回都是JSON

a).程序發起

index.jsp的一個按鈕

 

 

 

b).js函數

 

 

function requestByJson() {

         $.ajax({

                   type : 'post',

                   url : '${pageContext.request.contextPath}/jsonsource.action',

                   //設置contentType類型爲json

                   contentType : 'application/json;charset=utf-8',

                   //json數據

                   data : '{"username":"reader001","password":"psw001"}',

                   //請求成功後的回調函數

                   success : function(data) {

                            alert(data.username);

                   }

         });

}

 

c).Controller/Mapping

@RequestMapping("/jsonsource")

//@RequestBody 將json對象轉成java對象

//@ResponseBody 表示返回的是json對象

public @ResponseBody User jsonSource(@RequestBody User user){

        

         return user;

}

 

d).測試結果

查看瀏覽器的開發者工具信息

request

 

 

response

 

 

PS:User類有3個屬性,id,username,password。

回調函數使用alert(data.username);

 

 

 

二、請求是key/value值,返回JSON

a).程序發起

 

 

b).js函數

//請求是key-value的值,返回的是json

function resquestByKV() {

         $.ajax({

                   type : 'post',

                   url : '${pageContext.request.contextPath}/kvsource.action',

                   data : 'username=kvuser&password=kvpsw',

                   success : function(data) {

                            alert(data.username);

                   }

         });

}

c).Controller/Mapping

 

 

參數沒有@RequestBody。

 

d).測試結果

參考1。

 

 

3、提交表單數據,返回json結果。

一、實驗準備和預測

設計兩個form,將form1的數據提交後,作必定的處理後返回到form2。處理結果依據controller。

 

 

 

二、將數據做爲json發出

a).JS函數

 

 

b).Controller

 

 

 

c).結果

 

 

 

實驗過程,發現若是要傳遞json數據(java程序傳出),因爲json的字符串要在雙引號中,要達到雙引號的效果,引號較混亂。

三、將數據做爲key/value的形式發出。

a).JS函數

 

 

 

b).Controller

 

 

c).結果

 

 

 

 

4、Spring mvc和ajax中文亂碼問題

一、返回的java對象

若是是java對象做爲json對象返回的話,不須要設置過濾器,spring的配置文件也沒有設置字符編碼,中文正常返回。估計是json的支持包或spring有編碼的設置。

 

二、返回字符串

例子請求的是這個方法

 

 

 

a).設置filter字符編碼

spring的字符過濾器org.springframework.web.filter.CharacterEncodingFilter

 

無效,是亂碼。顯示以下

 

 

 

b).解決方法1、@ResponseBody

加上produces。如produces="application/json; charset=utf-8"。

 

 

設置後沒有亂碼

 

 

c).解決方法2、mvc:annotation-driven

這個方法是針對全部。

在mvc:annotation-driven加上下面的StringHttpMessageConverter

 

主要是text/html;charset=UTF-8就能夠,其餘都不能夠。避免亂碼。

 

<mvc:annotation-driven>

<mvc:message-converters register-defaults="true">

         <bean class="org.springframework.http.converter.StringHttpMessageConverter">

                   <property name="supportedMediaTypes"> 

    <list> 

         <!--application/json和text/plain沒法解決返回字符串的亂碼  -->

         <!-- <value>application/json;charset=UTF-8</value> 

          <value>text/plain;charset=UTF-8</value>

          -->

         <value>text/html;charset=UTF-8</value>

    </list> 

</property>

         </bean>

</mvc:message-converters>

</mvc:annotation-driven>

發現:再去掉註解中的參數produces="application/json; charset=utf-8",而後測試。supportedMediaTypes加入text/html;charset=UTF-8能解決亂碼。且java對象的json返回也沒有出現亂碼問題。

相關文章
相關標籤/搜索