以前在采用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

Struts2自定义Result处理JSON的更多相关文章

  1. 扩展struts2的结果集StrutsResultSupport 自定义Result处理JSON

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

  2. jquery序列化from表单使用ajax提交返回json数据(使用struts2注解result type = json)

    1.action类引入struts2的"json-default"拦截器栈 @ParentPackage("json-default") //示例 @Paren ...

  3. Struts2 中 result type=”json” 的参数解释

    转自:http://wangquanhpu.iteye.com/blog/1461750 1, ignoreHierarchy 参数:表示是否忽略等级,也就是继承关系,比如:TestAction 继承 ...

  4. Struts2 自定义Result

    注意:我只要是解决自定义返回Json 和异常处理问题 新建一个类 AjaxResult   继承 StrutsResultSupport 看看代码吧 public class AjaxResult e ...

  5. Struts2自定义返回Json类型result

    本来Struts2有自己的json类型的返回结果,并提供了插件,但是它有一个问题,那就是它会将所有序列化的字段都返回,如果想要制定返回Action的某一个属性,则需要在配置result时,配置参数(这 ...

  6. Struts2 配置文件result的name属性和type属性

    Struts2 配置文件result的name属性和type属性:Name属性SUCCESS:Action正确的执行完成,返回相应的视图,success是 name属性的默认值: NONE:表示Act ...

  7. Struts2配置RESULT中TYPE的参数说明

    chain           用来处理Action链,被跳转的action中仍能获取上个页面的值,如request信息.           com.opensymphony.xwork2.Acti ...

  8. Struts2自定义拦截器Interceptor以及拦截器登录实例

    1.在Struts2自定义拦截器有三种方式: -->实现Interceptor接口 public class QLInterceptorAction implements Interceptor ...

  9. Caused by: The Result type [json] which is defined in the Result annotation on the class

    1.错误描述 严重: Dispatcher initialization failed Unable to load configuration. - [unknown location] at co ...

随机推荐

  1. JavaScript 中typeof、instanceof 与 constructor 的区别?

    typeof.instanceof 与 constructor 详解 typeof  一元运算符 返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,st ...

  2. git团队开发

    用git有一年了,下面是我这一年来的git使用总结,覆盖了日常使用中绝大多数的场景.嗯,至少是够用一年了,整理出来分享给大家,不明白的地方可以回复交流. git设置关闭自动换行 git config ...

  3. Python 的十个自然语言处理工具

    原文 先mark,后续尝试. 1.NLTK NLTK 在用 Python 处理自然语言的工具中处于领先的地位.它提供了 WordNet 这种方便处理词汇资源的借口,还有分类.分词.除茎.标注.语法分析 ...

  4. [实战]MVC5+EF6+MySql企业网盘实战(17)——思考2

    写在前面 今天吃饭回来,突然有一个更好的想法,这里做一下记录. 系列文章 [EF]vs15+ef6+mysql code first方式 [实战]MVC5+EF6+MySql企业网盘实战(1) [实战 ...

  5. Python爬虫-urllib的基本用法

    from urllib import response,request,parse,error from http import cookiejar if __name__ == '__main__' ...

  6. 三 Python解释器

    当我们编写Python代码时,我们得到的是一个包含Python代码的以.py为扩展名的文本文件.要运行代码,就需要Python解释器去执行.py文件. 由于整个Python语言从规范到解释器都是开源的 ...

  7. (9) go 时间日期

    1. var t = time.Now() println(t.String())//2019-04-26 13:38:02.5100554 +0800 CST m=+0.000000001 2. 月 ...

  8. python中if和elif的区别

    多个if语句是每次单独判断 比如: 例子一: a = 5 if a < 6: #条件1 print(1) if a < 7: #条件2 print(2) else: print(3) 条件 ...

  9. cogs——2098. Asm.Def的病毒

    2098. Asm.Def的病毒 ★☆   输入文件:asm_virus.in   输出文件:asm_virus.out   简单对比时间限制:1 s   内存限制:256 MB [题目描述] “这就 ...

  10. openstack newton linuxbridge 改成 ovs

    最近搭建了一个all in one 的 openstack newton 版,安装官方文档做用的是linuxbridge.已经老版玩的时候都是用的ovs,趁比较闲的时候也将N版改造一下 官方文档 ht ...