然然爱问

导航

Struts2+JSON+jQuery实现异步交互

      使用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         //用户1
41         User user1=new User();
42         user1.setUserId(1);
43         user1.setUserName("艾广然");
44         user1.setPassword("123456");
45         
46         //用户2
47         User user2=new User();
48         user2.setUserId(2);
49         user2.setUserName("王宁");
50         user2.setPassword("654321");
51         
52         //将对象存入到list
53         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表示不包含的属性(可以使用正则表达式匹配),剩下的属性将被序列化 -->  
14                 <param name="excludeProperties">  
15                     address,uuid
16                 </param>  
17                 <!-- includeProperties表示包含序列化的属性(可以使用正则表达式匹配),没写的不会被序列化,这里要写list.*,否则前台不能获取到 -->  
18                 <param name="includeProperties">  
19                     list.*
20                 </param> 
21                 
22             </result>
23         </action>
24     </package>
25 </struts>

excludeProperties和includeProperties使用一个就可以了。如果向前台传递的值多,就使用excludeProperties排除前台用不到的属性。如果传递的少,就使用includeProperties属性。

posted on 2013-03-19 23:51  然然爱问  阅读(2587)  评论(0编辑  收藏  举报