ㄓㄤㄑㄧㄤ

Struts2自定义Result处理JSON

以前在采用Struts2开发的项目中,对JSON的处理一直都在Action里处理的,在Action中直接Response,最近研读了一下Struts2的源码,发现了一个更加优雅的解决办法,自己定义一个ResultType,

首先大家先看下Struts2中的源码

包com.opensymphony.xwork2下的DefaultActionInvocation

472行

复制代码
/** 
 * Save the result to be used later. 
 * @param actionConfig current ActionConfig 
 * @param methodResult the result of the action. 
 * @return the result code to process. 
 */  
protected String saveResult(ActionConfig actionConfig, Object methodResult) {  
    if (methodResult instanceof Result) {  
        this.explicitResult = (Result) methodResult;  
  
        // Wire the result automatically  
        container.inject(explicitResult);  
        return null;  
    } else {  
        return (String) methodResult;  
    }  
}
复制代码

如果resultType实现了Result接口,则执行

this.explicitResult = (Result) methodResult;  
  
// Wire the result automatically  
container.inject(explicitResult);  
return null;  

现在我们来定义一个接口(JsonResult)来处理一般的POJO对象

复制代码
package com.kiloway.struts;  
  
import java.io.PrintWriter;  
  
import javax.servlet.http.HttpServletResponse;  
  
import net.sf.json.JSONObject;  
import net.sf.json.JsonConfig;  
  
import org.apache.struts2.ServletActionContext;  
import org.apache.struts2.dispatcher.StrutsResultSupport;  
  
import com.opensymphony.xwork2.ActionInvocation;  
  
public class JsonResult extends StrutsResultSupport {  
  
    private Object result;  
    private JsonConfig jsonConfig;  
  
    public Object getResult() {  
        return result;  
    }  
  
    public JsonResult(JsonConfig jsonConfig) {  
        super();  
        this.jsonConfig = jsonConfig;  
    }  
  
    public void setResult(Object result) {  
        this.result = result;  
    }  
  
    private static final long serialVersionUID = 7978145882434289002L;  
  
    @Override  
    protected void doExecute(String finalLocation, ActionInvocation invocation)  
            throws Exception {  
        HttpServletResponse response = null;  
        try {  
            response = ServletActionContext.getResponse();  
            PrintWriter printWriter = response.getWriter();  
            if (jsonConfig != null) {  
                printWriter.write(JSONObject.fromObject(result).toString());  
            } else {  
                printWriter.write(JSONObject.fromObject(result, jsonConfig)  
                        .toString());  
            }  
        }catch(Exception e){  
            throw new Exception("json parse error!");  
        } finally {  
            response.getWriter().close();  
        }
    }  
}  
复制代码

JsonReulst定义好了该如何让Struts处理呢?

我们在struts.xml里面可以这样定义

复制代码
<package name="default" namespace="/" extends="struts-default">  
        <result-types>  
            <result-type name="jsonResult" class="com.kiloway.struts.JsonResult"/>  
        </result-types>  
  
        <action name="student" class="com.kiloway.struts.Student">  
            <result name="json" type="jsonResult"/>  
        </action>  
</package> 
复制代码

reuslt的name可以任意,但type必须和你注册的ResultType相同。

Action 中直接这样调用

复制代码
public JsonResult getJson()  
    {  
        UserInfo f = new UserInfo();  
        f.setName("小睿睿");  
        f.setPassword("哈哈");  
        JsonResult jsonResult  = new JsonResult();  
        jsonResult.setResult(f);  
        return jsonResult;  
    }  
复制代码

在我们的Action代码中就不用response.write了,完全交给了Reuslt对象去处理了(doExecute)

这样就很方便的处理了JSON格式的数据

struts的开发包里,发现了一个JSON处理插件 struts2-json-plugin-2.3.8.jar

该插件提供了更完善的JSON处理解决方案。

原文http://blog.csdn.net/myxx520/article/details/8655088

 

posted @   ㄓㄤㄑㄧㄤ  阅读(1049)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一文搞懂MCP协议与Function Call的区别
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
哈哈,页脚部分。
点击右上角即可分享
微信分享提示