Struts2 扩展结果集(ajax取action的数据)(2)

上一章我们说了ajax取action数据的第一种方法,现在我们来介绍第二种比较好玩的方法,个人比较推荐,那就是struts2扩展结果集。

使用过struts2的童鞋都知道,我们在struts.xml里面可以选择不同的结果类型,常用的有dispatcher、redirect、chain、redirectAction、stream(文件流)。但这些都不能满足我们日常的需求,所以我们可以扩展结果集,编写一个适合自己开发的结果类型。

 

struts.xml

<package name="json" extends="struts-default" namespace="/json">
        <!-- 可以写在此处,如果是常用的,建议写在struts-plugin.xml里面,这里不作演示 -->
        <result-types>
            <result-type name="jsonObject" class="com.lee.cnblogs.JsonObjectResult"></result-type>
        </result-types>
        
        <action name="getJson">
            <result type="jsonObject">
                <param name="name">"lee"</param><!-- 此处可以从后台action里面接收 -->
            </result>
        </action>
 </package>

 

class

public class JsonObjectResult extends StrutsResultSupport {

    private String name;
    private String contentTypeName;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContentTypeName() {
        return contentTypeName;
    }
    public void setContentTypeName(String contentTypeName) {
        this.contentTypeName = contentTypeName;
    }
    
    protected void doExecute(String location, ActionInvocation actionInvocation)
            throws Exception {
        
        HttpServletResponse response = (HttpServletResponse) actionInvocation.getInvocationContext()
                                    .get(StrutsStatics.HTTP_RESPONSE);
        String contentType = this.conditionalParse(contentTypeName, actionInvocation);
        if (contentType == null) {
            contentType = "text/javascript; charset=UTF-8";
        }
        
        response.setContentType(contentType);
        
        Object result = actionInvocation.getStack().findValue(name);
        
        StringBuffer sb = new  StringBuffer();
        
        //如果是字符串
        if(result instanceof String) {
            sb.append(result);
        }
        //如果是数组或者集合对象
        else if(result instanceof Arrays || result instanceof Collection) {
            sb.append(JSONArray.fromObject(result).toString());
        }
        //如果是其他对象
        else {
            sb.append(JSONObject.fromObject(result).toString());
        }
        
        PrintWriter out = response.getWriter();
        out.println(sb.toString());
        out.flush();
        out.close();
    }

}

 

jsp

$(document).ready(function() {
                
        $.ajax({
            async : false,
            type: 'POST',
            dataType:"json",
            url:"json/getJson.action",
            success:function(result) {
                    alert(result);
            },
            failure:function() {
                    alert("fail");
            }
        });
});

 

注:具体的配置仍需修改,这里就不一一阐述了。

posted on 2014-04-12 20:31  洋葱lee  阅读(474)  评论(0)    收藏  举报

导航