---
title: "关于json与struts2进行数据交互 (2010-11-02 20:17:33) 转载 标签： 杂谈 \t分类： java技术 为了怕以后的开发中出现同样的问"
author: "endual"
date: "2011-06-26T21:20:36Z"
tags: ["Ajax", "Java", "Struts", "json", "正则表达式"]
categories: ["企业架构"]
slug: "json-struts2-2010-11-02-20-17-33-java"
draft: false
lastmod: "2012-03-04T13:48:45Z"
id: 1105566
url: "https://endual.iteye.com/blog/1105566"
---

## 关于json与struts2进行数据交互

(2010-11-02 20:17:33)

[![](http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif) 转载]()

标签：

### [杂谈](http://uni.sina.com.cn/c.php?t=blog&k=%D4%D3%CC%B8&ts=bpost&stype=tag)

分类： [java技术](http://blog.sina.com.cn/s/articlelist_1745908437_1_1.html)

为了怕以后的开发中出现同样的问题，现将问题记录起来  
关于json与struts交互的问题  
前台技术采用extjs:  
strut2提供了支持json的插件  
必须继承json-default、json-default继承自struts-default.  
&lt;package name="json" namespace="/" extends="json-default"&gt;

&lt;action name="moduleAction" class="moduleAction" &gt;

 

              &lt;result type="json" name="findData"&gt;  
                 &lt;param name="root"&gt;datas&lt;/param&gt;  
                 &lt;param name="includeProperties"&gt;success,totalcount&lt;/param&gt;  
               &lt;/result&gt;

               &lt;result type="json" name="findTree"&gt;  
                 &lt;param name="root"&gt;result&lt;/param&gt;  
               &lt;/result&gt;  
&lt;/action&gt;

1,result中type设置成json之后，容器会把action的属性自动封装到一个json对象中（json拦截器来做），然后调用ajax的callback方法. 返回json数据

2,includeProperties 参数：输出结果中需要包含的属性值，这里正则表达式和属性名匹配，可以用“,”分割填充多个正则表达式。  
  如&lt;param name="includeProperties"&gt;module.\*,user\\.userName&lt;/param&gt;  表示是module的所有属性及用户的用户名

3,excludeProperties 参数：输出结果需要排除的属性值，也支持正则表达式匹配属性名，可以用“,”分割填充多个正则表达式，类同includeProperties

4，为什么要用includeProperties或excludeProperties 参数：  
     主要是为了过滤掉接口，pojo的set、list、其它对象等不需要的数据防止循环取其它关联对象或找不到接口。

     如果不配置,默认是处理 action中的所有属性，如果action中有接口注入，json拦截器可能找不到接口而返回不了结果，

    还有如果action中有一个对象，这个对象与好多对象都有关联，json拦截器会将相关联的所有对象的属性全部转换成json格式，

    如果其它对象有list、set,其返回结果相当庞大，有可能是死循环而无法返回 。

   如果不用&lt;param name="includeProperties"&gt;或其他方式进行json数据过滤，通过debug你会发现前台返回的json字符串，

   是把 action中的所有属性全部转化成json字符串返回给客户端

 （包括service接口、pojo所有属性及有关联的pojo。有时候根本返回不了结果，也不报错，后台执行了，

  但前台执行不到callback function，这主要是因为找不到接口或者关联的pojo太多，造成死循环），

  一般情况下用的最多的就是root、 includeProperties 和excludeNullProperties参数。

  当然还有其他的方法，如给pojo的属性加json注解。

5,result标签中的name属性，即表示是struts2中的action类中返回的名称  
如  
     public String findAllById() throws Exception{  
      int id=Integer.parseInt( this.request.getParameter("pid"));  
       List&lt;ModuleBean&gt; list=service.findById(id);  
       return "findTree";  
   }  
 上面代码return "findTree"就会找到findTree的结果集，并将其封装起来，返回json给客户端

因此 action 可以配置多个result