`

Struts2的Ajax应用

 
阅读更多

一、基本原理

使用拦截器机制,对Action的成员变量做持久化处理。

 

 

二、包的设置

<package.../>元素的属性extends为“json-default”,“json-default”的result type可以为“json”。

json-default 设置后,result就会被Struts2的拦截器拦截。并按json序列化后返回。

 视图为Action的字段,且字段按JSON格式序列化输出给客户端全部字段输出

 

三、指定序列化字段

解决方案:

在struts2.xml配置文件中里配置

        <param name="includeProperties"></param> 这个属性表示要包含进JSON数据中的数据。

        <param name="excludeProperties"></param> 这个属性表示不要包含进JSON数据中的数据。

注意:

Jar包是jsonplugin-0.25的,只支持excludeProperties,不支持includeProperties。

从0.28版本才开始支持includeProperties。

 

讨论:

只要有get方法,都会包含到json对象的属性,比如此useraction转为json如下:

{"allDatas":null,"analysisList":null,"maps":{6388:170},"message":null,"model":{"attachName":null,"attachPath":null,"auditStatus":null,"briefTitle":"null"}"

有时候我们只想指定的字段转为json,这时需要在xml里配置<param name="includeProperties">。

例:xml配置

<package name="example"  extends="json-default">
   <action name="JSONExample" class="com.test.UserAction">
     <result type="json">
       <param name="includeProperties">
         name,maps.*
       </param>
     </result>
   </action>
</package>
 

例如:配置返回refreshDatas集合中的字段

<action name="vote" class="com.test.VoteAction" method="{1}">
    <result name="error" type="json">
        <param name="includeProperties">message</param>
    </result>
    <result name="success" type="json">
        <param name="includeProperties">message,refreshDatas\[\d+\]\.newsId,refreshDatas\[\d+\]\.numberOfVotes</param>
    </result>
</action>

 


四、指定非序列化字段

为了使Action类的某些对象不序列化,则只需要字段不提供get方法即可。

或使用@JSON(serialize=false) ,或使用@Transient注解该字段。

@JSON和json类型的result都还有很多可选项,无非就是串行化谁,不串行化谁,返回数据的MIME类型,读者可以自行参考相关文档。

 

 

 

参考文档:

http://bosslife.blog.163.com/blog/static/114917017201061911130625/

http://bangsen.iteye.com/blog/969353

http://topic.csdn.net/u/20091214/14/c57aa29d-2588-473c-8e17-032e35a8e696.html

http://wenku.baidu.com/view/26d9a9f67c1cfad6195fa734.html

http://struts.apache.org/2.2.3/docs/json-plugin.html 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics