以前在采用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. vuejs学习——vue+vuex+vue-router项目搭建(二)

    前言 最近比较忙,所有第二章发布晚了,不好意思各位. vuejs学习——vue+vuex+vue-router项目搭建(一) 中我们搭建好了vue项目,我相信大家已经体验了vue其中的奥妙了,接下来我 ...

  2. git客户端基本操作

    首先下载git 一路next安装好了之后,打开任意盘符,右键打开git bash here 首先:初始首次的用户名和邮箱,之后就不用了. git config --global user.name & ...

  3. ref:Adding AFL Bloom Filter to Domato for Fun

    ref:https://www.sigpwn.io/blog/2018/5/13/adding-afl-bloom-filter-to-domato-for-fun Adding AFL Bloom ...

  4. ArrayBuffer对象、TypedArray视图和DataView视图

    转:http://es6.ruanyifeng.com/#docs/arraybuffer ArrayBuffer ArrayBuffer 对象 TypedArray 视图 复合视图 DataView ...

  5. google::proto::message.h

    整了一阵子google  proto message.h, 遇到很多问题,各种百度.google ,估计是用的人不是很多,整的焦头烂额,很多API都不知道该怎么用,只能一点一点的扣,为了方便在这里先简 ...

  6. Python类总结-封装(私有属性,方法)

    封装基础 广义上面向对象的封装:代码的保护,面向对象的思想本身就是一种封装 只让自己的对象能调用自己类中的方法 狭义上的封装-面向对象三大特性之一(私有变量,用公有的方法封装私有属性,方法叫封装) 把 ...

  7. vue-router在IE11中页面不跳转

    情景: IE11浏览器中,在进行正常页面跳转操作后(页面A跳转到页面B),点击浏览器的左上角的‘后退’按钮,点击后,可以看到url地址已经发生了变化(url由页面B变为页面A),hash值也已经是上一 ...

  8. 折半搜索【p4799】[CEOI2015 Day2]世界冰球锦标赛

    Description 今年的世界冰球锦标赛在捷克举行.Bobek 已经抵达布拉格,他不是任何团队的粉丝,也没有时间观念.他只是单纯的想去看几场比赛.如果他有足够的钱,他会去看所有的比赛.不幸的是,他 ...

  9. 使用webgl(three.js)创建3D机房,3D机房微模块详细介绍(升级版二)

    序: 上节课已经详细描述了普通机房的实现过程,文章地址(https://www.cnblogs.com/yeyunfei/p/10473021.html) 紧接着上节课的内容 我们这节可来详细讲解机房 ...

  10. debug id

    id是Eclipse的debugger自己生成的,用于告诉你哪些变量是指向同一个对象:id相同即指向同一个对象. primitive不是对象,所以就没有id. 但是如果你用primitive的wrap ...