Struts2+JSON+jQuery實現非同步互動

來源:互聯網
上載者:User

      使用Struts2的JSON外掛程式,實現Action中的屬性序列化成JSON對象時預設JSON外掛程式會把所有Action中包含getter方法的屬性都序列化到JSON對象中。但是有時候我們並不需要太多的屬性,或者只需要一個屬性。那麼怎樣控制屬性序列化到JSON對象中哪?Struts2的JSON外掛程式為我們提供了兩種方式:第一:使用Struts2的struts.xml設定檔的方式。第二:使用註解的方式控制

 

首先我建立的目錄結構圖以及需要的jar包:

 

第一:使用Struts2的struts.xml設定檔的方式:

index頁面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">                <script type="text/javascript" src="<%=path %>/js/jquery.js"></script>    <script type="text/javascript">$(function(){    //為擷取List對象按鈕添加按一下滑鼠事件    $("#getList").click(function(){        $.getJSON("jsontest!returnList.action",function(data){            //清空顯示層中的資料            $("#message").html("");            //使用jQuery中的each(data,function(){});方法            //從data.list擷取User對象放入value之中            $.each(data.list,function(i,value){                $("#message").append("<div>第"+(i+1)+"個使用者:</div>")                         .append("<div><font color='red'>使用者ID:"+value.userId+"</font></div>")                         .append("<div><font color='red'>使用者名稱:"+value.userName+"</font></div>")                         .append("<div><font color='red'>密碼:"+value.password+"</font></div>");            });        });    });})    </script>  </head>    <body>      <input id="getList" type="button" value="擷取List對象"/>     <!-- 要顯示資訊的層 -->    <div id="message"></div>  </body></html>

user.java中存放使用者的屬性

View Code

 1 package struts2jsonjquery.entity; 2  3 import java.io.Serializable; 4 public class User implements Serializable { 5  6     private static final long serialVersionUID = 3952189513312630860L; 7      8     private int userId; 9     private String userName;10     private String password;11     public int getUserId() {12         return userId;13     }14     public void setUserId(int userId) {15         this.userId = userId;16     }17     public String getUserName() {18         return userName;19     }20     public void setUserName(String userName) {21         this.userName = userName;22     }23     public String getPassword() {24         return password;25     }26     public void setPassword(String password) {27         this.password = password;28     }29 }

action中:

View Code

 1 package struts2jqueryjson.action; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 import struts2jsonjquery.entity.User; 7  8 import com.opensymphony.xwork2.ActionSupport; 9 10 public class JsonJQueryStruts2Action extends ActionSupport{11     12 13 /**14  * Struts2的JSON外掛程式,實現Action中的屬性序列化成JSON對象時預設JSON外掛程式會把所有Action中包含getter方法的屬性都序列化到JSON對象中15  * */16     17     private int uuid;18     public int getUuid() {19         return uuid;20     }21 22     23     private String address;24     public String getAddress() {25         return address;26     }27 28     29     private List<User> list;30     public List<User> getList() {31         return list;32     }33 /**34  * ==================================35  */36     37     public String returnList(){38         list=new ArrayList();39         40         //使用者141         User user1=new User();42         user1.setUserId(1);43         user1.setUserName("艾廣然");44         user1.setPassword("123456");45         46         //使用者247         User user2=new User();48         user2.setUserId(2);49         user2.setUserName("王寧");50         user2.setPassword("654321");51         52         //將對象存入到list53         list.add(user1);54         list.add(user2);55         56         return "userList";57         58         59         60     }61 62 63 64 65     66     67     68 69 70 }

struts.xml中:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4     "http://struts.apache.org/dtds/struts-2.0.dtd"> 5  6 <struts> 7  8     <package name="default" namespace="/" extends="json-default"> 9         <action name="jsontest" class="struts2jqueryjson.action.JsonJQueryStruts2Action">10             <!-- 擷取action中所有有get方法的屬性,自動轉換為json對象 -->11             <result name="userList" type="json">12 13             </result>14         </action>15     </package>16 </struts>

可以看到這裡已經擷取到了全部的get方法。

但是有時候前台並不需要那麼多資料,所以修改了struts.xml設定檔:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4     "http://struts.apache.org/dtds/struts-2.0.dtd"> 5  6 <struts> 7  8     <package name="default" namespace="/" extends="json-default"> 9         <action name="jsontest" class="struts2jqueryjson.action.JsonJQueryStruts2Action">10             <!-- 返回List對象,類型指定為json自動轉換 -->11             <result name="userList" type="json">12             13             <!-- excludeProperties表示不包含的屬性(可以使用Regex匹配),剩下的屬性將被序列化 -->  14                 <param name="excludeProperties">  15                     address,uuid16                 </param>  17                 <!-- includeProperties表示包含序列化的屬性(可以使用Regex匹配),沒寫的不會被序列化,這裡要寫list.*,否則前台不能擷取到 -->  18                 <param name="includeProperties">  19                     list.*20                 </param> 21                 22             </result>23         </action>24     </package>25 </struts>

excludeProperties和includeProperties使用一個就可以了。如果向前台傳遞的值多,就使用excludeProperties排除前台用不到的屬性。如果傳遞的少,就使用includeProperties屬性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.