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

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

包com.opensymphony.xwork2下的DefaultActionInvocation

472行

  1. /**
  2. * Save the result to be used later.
  3. * @param actionConfig current ActionConfig
  4. * @param methodResult the result of the action.
  5. * @return the result code to process.
  6. */
  7. protected String saveResult(ActionConfig actionConfig, Object methodResult) {
  8. if (methodResult instanceof Result) {
  9. this.explicitResult = (Result) methodResult;
  10. // Wire the result automatically
  11. container.inject(explicitResult);
  12. return null;
  13. } else {
  14. return (String) methodResult;
  15. }
  16. }

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

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

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

  1. package com.kiloway.struts;
  2. import java.io.PrintWriter;
  3. import javax.servlet.http.HttpServletResponse;
  4. import net.sf.json.JSONObject;
  5. import net.sf.json.JsonConfig;
  6. import org.apache.struts2.ServletActionContext;
  7. import org.apache.struts2.dispatcher.StrutsResultSupport;
  8. import com.opensymphony.xwork2.ActionInvocation;
  9. public class JsonResult extends StrutsResultSupport {
  10. private Object result;
  11. private JsonConfig jsonConfig;
  12. public Object getResult() {
  13. return result;
  14. }
  15. public JsonResult(JsonConfig jsonConfig) {
  16. super();
  17. this.jsonConfig = jsonConfig;
  18. }
  19. public void setResult(Object result) {
  20. this.result = result;
  21. }
  22. private static final long serialVersionUID = 7978145882434289002L;
  23. @Override
  24. protected void doExecute(String finalLocation, ActionInvocation invocation)
  25. throws Exception {
  26. HttpServletResponse response = null;
  27. try {
  28. response = ServletActionContext.getResponse();
  29. PrintWriter printWriter = response.getWriter();
  30. if (jsonConfig != null) {
  31. printWriter.write(JSONObject.fromObject(result).toString());
  32. } else {
  33. printWriter.write(JSONObject.fromObject(result, jsonConfig)
  34. .toString());
  35. }
  36. }catch(Exception e){
  37. throw new Exception("json parse error!");
  38. } finally {
  39. response.getWriter().close();
  40. }
  41. }
  42. }

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

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

  1. <package name="default" namespace="/" extends="struts-default">
  2. <result-types>
  3. <result-type name="jsonResult" class="com.kiloway.struts.JsonResult"/>
  4. </result-types>
  5. <action name="student" class="com.kiloway.struts.Student">
  6. <result name="json" type="jsonResult"/>
  7. </action>
  8. </package>

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

Action 中直接这样调用

  1. public JsonResult getJson()
  2. {
  3. UserInfo f = new UserInfo();
  4. f.setName("小睿睿");
  5. f.setPassword("哈哈");
  6. JsonResult jsonResult  = new JsonResult();
  7. jsonResult.setResult(f);
  8. return jsonResult;
  9. }

在我们的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的结果集StrutsResultSupport 自定义Result处理JSON的更多相关文章

  1. Struts2自定义Result处理JSON

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

  2. JavaWeb_(Struts2框架)Action中struts-default下result的各种转发类型

    此系列博文基于同一个项目已上传至github 传送门 JavaWeb_(Struts2框架)Struts创建Action的三种方式 传送门 JavaWeb_(Struts2框架)struts.xml核 ...

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

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

  4. 【bzoj4869】[Shoi2017]相逢是问候 扩展欧拉定理+并查集+树状数组

    题目描述 Informatik verbindet dich und mich. 信息将你我连结. B君希望以维护一个长度为n的数组,这个数组的下标为从1到n的正整数.一共有m个操作,可以分为两种:0 ...

  5. 制作ACK集群自定义节点镜像的正确姿势

    随着云原生时代的到来,用户应用.业务上云的需求也越来越多,不同的业务场景对容器平台的需求也不尽相同,其中一个非常重要的需求就是使用自定义镜像创建ACK集群. ACK支持用户使用自定义镜像创建Kuber ...

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

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

  7. springmvc 自定义view支持json和jsonp格式数据返回

    1.如果controlloer上用@ResponseBody注解,则用<mvc:message-converter>里面配置的json解析器进行解析 <mvc:annotation- ...

  8. 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 ...

  9. Loadrunner请求自定义的http(json)文件and参数化

    Loadrunner请求自定义的http(json)文件and参数化      研究啦好些天这个东西啦 终于出来答案啦 嘿嘿 给大家分享一下 : 请求自定义的http文件用函数:web_custom_ ...

随机推荐

  1. Html一天入门

    一.什么是HTML 1.html: HyperText Markup Language 超文本标记语言,是最基础的网页语言,而且都是由标签组成. 2.基本格式: <html> <he ...

  2. finally关键字

    final:禁止多态开关~修饰变量:变量不能被改变修饰类:类不能被继承修饰方法:方法不能被重写 finally:用在异常处理的最后一个语句块无论是否产生异常都要被执行~~~ Java代码 public ...

  3. 关于如何获取第三方app包内图片资源的方法

    如果想获取其他app的图片资源,简直是易如反掌,如下提供两种方法,其实本质上是一种方法. 方法一: First:登陆itunes,在itunes里的appstore栏找到已购项目,里面有你的账号所下载 ...

  4. 【BZOJ-1717】Milk Patterns产奶的模式 后缀数组

    1717: [Usaco2006 Dec]Milk Patterns 产奶的模式 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 881  Solved:  ...

  5. ZendGuardLoader安装

    遇到的问题 php -v Zend Guard Loader requires Zend Engine API version 220090626. The Zend Engine API versi ...

  6. HDU4612 Warm up

    Time Limit: 5000MS   Memory Limit: 65535KB   64bit IO Format: %I64d & %I64u Description N planet ...

  7. Linux Network Related Drive

    catalog . 通过套接字通信 . 网络实现的分层模型 . 网络命名空间 . 套接字缓冲区 . 网络访问层 . 网络层 . 传输层 . 应用层 . 内核内部的网络通信 1. 通过套接字通信 Lin ...

  8. PHP预定义接口

    目录 引言 IteratorAggregate(聚合式aggregate迭代器Iterator) Countable ArrayAccess Iterator 总结 引言 在PHP中有好几个预定义的接 ...

  9. Android中运行的错误:java.lang.UnsatisfiedLinkError: Couldn't load locSDK3: findLibrary returned null.

    ---恢复内容开始--- 明明已经加入了liblocSDK3.so,但总是无法定位.提示错误java.lang.UnsatisfiedLinkError: Couldn't load locSDK3: ...

  10. 事务块TransactionScope使用

    TransactionScope 可以让代码块成为事务性代码块. 当发生异常时,会自动回滚.后期手动提交事务. 简单的例子: using (TransactionScope ts = new Tran ...