曾经在选用Struts2开发的项目中,对JSON的处置一贯都在Action里处置的,在Action中直接Response,比来研读了一下Struts2的源码,发现了一个越发高雅的解决办法,我的界说一个ResultType, 首要我们先看下Struts2中的源码 包com.opensymphony.xwork2下的DefaultActionInvocation 472行 /** * http://www.star1111.info/linked/20130309.do 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里边可以这样界说 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://www.haofapiao.com/linked/20130309.do