日期:2014-05-16  浏览次数:20435 次

struts2 使用json
JSON(Java Script Object Notation),是一种语言无关的数据交换格式。 JSON插件是Structs 2 的Ajax插件,通过利用JSON插件,开发者可以很方便,灵活的利用Ajax进行开发。 Json是一种轻量级的数据交换格式,JSon插件提供了一种名为json的Action ResultType 。 一旦为Action指定了该结果处理类型,JSON插件就会自动将Action里的数据序列化成JSON格式的数据, 并返回给客户端物理视图的JavaScript。简单的说,JSON插件允许我们在JavaScript中异步的调用Action,而且Action不需要指定视图来显示Action的信息显示。 而是由JSON插件来负责具体将Action里面具体的信息返回给调用页面。 Json的数据格式可简单如下形式: person = { name: 'Jim',age: 18,gender: 'man'}。 如果action的属性很多,我们想要从Action返回到调用页面的数据。 这个时候配置includeProperties或者excludeProperties拦截器即可。
而这2个拦截器的定义都在struts2的json-default包内,所以要使用该拦截器的包都要继承自json-default。
<struts>
    <constant name="struts.objectFactory" value="spring"/>    
    <include file="struts-admin.xml"></include>
    <package name="default" extends="json-default">
        <action name="person" class="com.person.PersonAction" method="view">
        <result type="json">
           <param name="includeProperties">          
            person\.name,persoon\.age,person\.gender          
           </param>>          
        </result>
        </action>
    </package>      
</struts>
利用Struts 2的支持的可配置结果,可以达到过滤器的效果。Action的处理结果配置支持正则表达式。
但是如果返回的对象是一个数组格式的Json数据。比如peson Bean中有对象persion1...person9,而我只要person1的json数据,
则可以用如下的正则表达式。
<struts>
    <constant name="struts.objectFactory" value="spring"/>    
    <include file="struts-admin.xml"></include>
    <package name="default" extends="json-default">
        <action name="person" class="com.person.PersonAction" method="view">
        <result type="json">
           <param name="includeProperties">          
            person\[\d+\]\.person1
           </param>>          
        </result>
        </action>
    </package>      
</struts>
excludeProperties拦截器的用法与此类同,如果拦截的仅仅是一个对象,如果拦截掉person Bean的整个对象,使用如下配置
<struts>
    <constant name="struts.objectFactory" value="spring"/>    
    <include file="struts-admin.xml"></include>
    <package name="default" extends="json-default">
        <action name="person" class="com.person.PersonAction" method="view">
        <result type="json">
           <param name="excludeProperties">          
            person
           </param>>&nb