Struts2之—集成Json插件實現Ajax

   上篇博客介紹了Struts2中自定義結果集實現Ajax,也分析了它的缺點:這樣自定義的結果集,寫死了,不能做到客戶端需要什麼數據就傳什麼數據; Struts2之—自定義結果集實現ajax

   本篇博客提出Struts2的集成Json插件,很好的解決了自定義結果集帶來的問題。

一,引題

1Json數據格式簡介

因爲JSON是脫離語言的理想的數據交換格式,所以它被頻繁的應用在客戶端與服務器的通信過程中,這一點是毋庸置疑的。而在客戶端與服務器的通信過程中,JSON數據的傳遞又被分爲服務器向客戶端傳送JSON數據,和客戶端向服務器傳送JSON數據,前者的核心過程中將對象轉換成JSON,而後者的核心是將JSON轉換成對象,這是本質的區別。另外,值得一提的是,JSON數據在傳遞過程中,其實就是傳遞一個普通的符合JSON語法格式的字符串而已,所謂的“JSON對象”是指對這個JSON字符串解析和包裝後的結果

2,Struts2返回JSON數據到客戶端

這是最常見的需求,在AJAX大行其道的今天,向服務器請求JSON數據已成爲每一個WEB應用必備的功能。拋開Struts2暫且不提,在常規WEB應用中由服務器返回JSON數據到客戶端有兩種方式:一是在Servlet中輸出JSON串,二是在JSP頁面中輸出JSON串。上文提到,服務器像客戶端返回JSON數據,其實就是返回一個符合JSON語法規範的字符串,所以在上述兩種方法中存在一個共同點,就是將需要返回的數據包裝稱符合JSON語法規範的字符串後在頁面中顯示。

3StrutsAction使用傳統方式返回json數據

省略。。。。。

4Struts集成Json插件,配置json格式結果集,返回json數據

     JSON插件是Structs 2 的Ajax插件,通過利用JSON插件,開發者可以很方便,靈活的利用Ajax進行開發。 

Json是一種輕量級的數據交換格式,JSon插件提供了一種名爲json的Action ResultType 。

 

     使用此結果集的好處:將轉換JSON數據的工作交給Struts2來做,與Action中以傳統方式輸出JSON不同的是,Action只需要負責業務處理,而無需關心結果數據是如何被轉換成JSON被返回客戶端的——這些 工作通過簡單的xml配置及jar包引用,Struts2會幫我們做的更好。

二,一,4的實現步驟:

1,引入Struts包、StrutsJson集成的jar包;struts-plugin.xml配置文件

——


——struts-plugin.xml:配置了集成的Json插件的信息(定義了名爲"json"的結果集,和名爲"json"的攔截器;注:具體json類型的結果集和攔截器Strutsjson插件已經實現了,我們只需在配置文件中將了實現類配置上即可);

 

<struts>
    <package name="json-default"extends="struts-default">
        <result-types>
             <!--名爲"json"的結果集-->  
            <result-typename="json" class="org.apache.struts2.json.JSONResult"/>
        </result-types>
        <interceptors>
            <!--名爲"json"的攔截器-->  
            <interceptorname="json"class="org.apache.struts2.json.JSONInterceptor"/>
        </interceptors>
    </package>
</struts>

2Web.xml

——配置Struts2的核心的過濾器

<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
<!-- 配置Struts2的核心的過濾器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> 
  <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3,用戶User類——實體類

private Long uid;//用戶id
private String username;//用戶名
private String sex;//性別

/************get/set方法*******************************************/</span>

publicLong getUid() {
returnuid;
}
publicvoid setUid(Long uid) {
this.uid= uid;
}
publicString getUsername() {
returnusername;
}
publicvoid setUsername(String username) {
this.username= username;
}
publicString getSex() {
returnsex;
}
publicvoid setSex(String sex) {
this.sex= sex;
}

4UserAction.java——處理業務,獲取用戶

importcom.opensymphony.xwork2.ActionSupport;
 
public classUserAction extends ActionSupport{
privateLong uid;
privateString username;
privateString password;
privateString sex;
privateString phone;
/**
 * 獲取用戶
 * @return
 */
publicString showUser(){
User user = new User();//創建一個User對象
user.setUid(1L);
user.setUsername("學敏");
   user.setSex("女");
user.setPassword("123");
user.setPhone("15466554589");
 
this.uid=user.getUid();
this.sex=user.getSex();
this.password=user.getPassword();
this.phone=user.getPhone();
this.username=user.getUsername();
 
returnSUCCESS;
}
/*******get/set方法**************************/        
publicLong getUid() {
returnuid;
}
 
publicvoid setUid(Long uid) {
this.uid= uid;
}
 
publicString getUsername() {
returnusername;
}
 
publicvoid setUsername(String username) {
this.username= username;
}
 
publicString getPassword() {
returnpassword;
}
 
publicvoid setPassword(String password) {
this.password= password;
}
 
publicString getSex() {
returnsex;
}
 
publicvoid setSex(String sex) {
this.sex= sex;
}
 
publicString getPhone() {
returnphone;
}
 
publicvoid setPhone(String phone) {
this.phone= phone;
}        
}

5,配置Strut2的配置文件Struts.xml

——繼承json-default,指定Action返回的結果集的類型爲:json;

<struts>
      <packagename="userjson" namespace="/"extends="json-default">
           <actionname="userJSONAction_*" method="{1}"class="cn.itcast.oa0909.struts2.action.UserAction">
                    <!--指定返回的結果集的類型爲:json -->
                  <resulttype="json"></result>
         </action>
     </package>
</struts>     

(注:一旦爲Action指定了該結果處理類型,JSON插件就會自動將Action裏的數據序列化成JSON格式的數據, 並返回給客戶端物理視圖的JavaScript。簡單的說,JSON插件允許我們在JavaScript中異步的調用Action 而且Action不需要指定視圖來顯示Action的信息顯示。 而是由JSON插件來負責具體將Action裏面具體的信息返回給調用頁面。)

6test.html頁面

<html>
  <head>
    <title>tree.html</title>
    <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
    <meta http-equiv="description"content="this is my page">
    <metahttp-equiv="content-type" content="text/html;charset=UTF-8">
  </head>
 
  <!--引入js文件 -->
  <scriptsrc="js/jquery-1.4.2.js"></script>
  <scriptsrc="js/test.js"></script>
 
  <body>
       This is my HTML page.
  </body>
</html>

7test.js文件

//頁面加載執行
$().ready(function(){
  
load();//調用load()函數
 
});        
functionload(){
 $.post("userJSONAction_showUser.action",null, function(data){     
            //彈出服務端返回的數據
 alert("編號:"+data.uid+",姓名:"+data.username+",性別:"+data.sex);
                   
     });
  }      


8,運行

地址:http://localhost:8080/Struts2+Ajax/test.html

 

結果:


 

三,json插件執行原理時序圖



四,總結

使用集成Json插件實現Ajax的好處

 

發佈了196 篇原創文章 · 獲贊 110 · 訪問量 98萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章