注意:我只要是解决自定义返回Json 和异常处理问题

新建一个类 AjaxResult   继承 StrutsResultSupport 看看代码吧

public class AjaxResult extends StrutsResultSupport {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
private static final String AJAX_SUCCESS = "{\"success\":true}";
private static final String SUCCESS_PERFIX = "{\"success\":true,result:[";
private static final String FAILURE_PERFIX = "{\"success\":false,result:[],";
private static final String SUFFIX = "]}";
private Writer writer;
private String defaultEncoding = "UTF-8"; @Inject("struts.i18n.encoding")
public void setDefaultEncoding(String encoding) {
this.defaultEncoding = encoding;
} protected void doExecute(String finalLocation, ActionInvocation invocation)
throws Exception {
Object action = invocation.getAction();
String responseData = "";
if ((action instanceof BaseAction)) {
BaseAction ajaxAction = (BaseAction) action;
HttpServletResponse response = ServletActionContext.getResponse();
String encoding = getEncoding(finalLocation);
String contentType = getContentType(finalLocation);
if (encoding != null) {
contentType = contentType + ";charset=" + encoding;
}
response.setContentType(contentType);
String successData = ajaxAction.getResponseData();
if (successData != null) {
if ("success".equals(successData)) {
responseData = "{\"success\":true}";
} else {
responseData = successData;
} }
// if(true){
// String errorResultLocation = ajaxAction.getErrorResultLocation();
// String exceptionMessage =
// invocation.getStack().findString("exception.message");
// exceptionMessage = exceptionMessage.replaceAll("\r", " ");
// exceptionMessage = exceptionMessage.replaceAll("\n", " ");
// exceptionMessage = exceptionMessage.replaceAll("\t", " ");
// responseData = getFailureData(null, exceptionMessage);
// }
getWriter().write(responseData);
}
} private String getFailureData(String errorResultLocation,
String exceptionMessage) {
String errors = "errors:[{msg:\"" + exceptionMessage + "\"}]";
// if (StringUtils.isNotBlank(errorResultLocation)) {
// String target = ",\"target\":\"" + errorResultLocation;
// return "{\"success\":false,result:[]," + errors + target + "\"}";
// } return "{\"success\":false,result:[]," + errors + "}";
} public void setWriter(Writer writer) {
this.writer = writer;
} protected Writer getWriter() throws IOException {
if (this.writer != null) {
return this.writer;
}
return ServletActionContext.getResponse().getWriter();
} protected String getContentType(String templateLocation) {
return "application/json";
} protected String getEncoding(String templateLocation) {
String encoding = this.defaultEncoding;
if (encoding == null) {
encoding = System.getProperty("file.encoding");
}
if (encoding == null) {
encoding = "UTF-8";
}
return encoding;
}
}

接下来,我们需要一个Struts 的配置文件

<package name="ajax-default" abstract="true" extends="struts-default">
<result-types>
<result-type name="ajax"
class="com.guy.core.common.util.AjaxResult" />
</result-types>
<global-results>
<result name="ajax" type="ajax" />
</global-results> </package>

之后我们新建一个公用类  BaseAction

public class BaseAction extends ActionSupport implements ModelDriven,SessionAware, ParameterAware, ServletRequestAware, ServletResponseAware{
/**
* serialVersionUID
*/
protected final Log logger = LogFactory.getLog(getClass());
private static final long serialVersionUID = 1L;
public String SUCCESS="SUCCESS";
public static final String AJAX = "ajax";
protected Map session;
protected Map parameters;
protected HttpServletRequest servletRequest;
protected HttpServletResponse servletResponse;
private String responseData;
protected void createJSonData(String jsonData) {
setResponseData(jsonData);
}
public String getResponseData() {
return responseData;
}
public void setResponseData(String responseData) {
this.responseData = responseData;
}
public Map getSession() {
return session;
}
public void setSession(Map session) {
this.session = session;
}
public Map getParameters() {
return parameters;
}
public void setParameters(Map parameters) {
this.parameters = parameters;
}
public HttpServletRequest getServletRequest() {
return servletRequest;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public HttpServletResponse getServletResponse() {
return servletResponse;
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
@Override
public Object getModel() {
return null;
} }

所有的action 都继承BaseAction   ModelDriven 我就不在解释了百度去

例如

public class LoginAction extends BaseAction{
 
createJSonData("{\"success\":false,\"msg\":\"密码错误。\"}");

return AJAX;

 

这样我们的  BaseAction  就完事了,

对象ToString 转成 json 格式了,方便查看

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
 1  <interceptor-ref name="landingIct">
2 <!-- 包括的方法,也就是拦截器拦截的方法<param name="includeMethods">方法1,方法2</param>
3
4 excludeMethods表示排除指定的方法,即不对标记为excludeMethods的方法进行拦截
5 -->
6 <param name="excludeMethods">landing</param>
7 </interceptor-ref>
8 <!-- 默认拦截器栈,如果不写则通过默认拦截器完成的功能将失效。如:国际化等等详细查看struts-default -->
9 <!--
10 如果action中没有自定义的拦截器,struts2会为该action添加默认的拦截器,即defaultStack;如果action中用户自己添加了自定义拦截器,将覆盖掉系统的defaultStack,这时候需要我们显式调用该拦截器栈。
11 -->

抛出异常  处理,在beasAction设置 IsAjaxError  AjaxErrorMessage

给get set 方法,

新建 AjaxExceptionInterceptor

 public String intercept(ActionInvocation invocation)
throws Exception
{
String result;
try
{
result = invocation.invoke();
}
catch (Exception e) {
if (this.logEnabled) {
handleLogging(e);
} List exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();
String mappedResult = findResultFromExceptions(exceptionMappings, e);
if (mappedResult != null) {
result = mappedResult;
Object action = invocation.getAction();
if (action instanceof AjaxProvider) {
AjaxProvider ajaxAction = (AjaxProvider)action;
Map results = invocation.getProxy().getConfig().getResults();
ResultConfig resultConfig = (ResultConfig)results.get(result);
String location = (String)resultConfig.getParams().get("location"); ajaxAtion.setIsAjaxError ("true");
ajaxAction.setAjaxErrorMessage(location);
result = "ajaxError";
}
super.publishException(invocation, new ExceptionHolder(e));
}
else {
throw e;
}
} return result;
}

baseAction  这里判断下是否有异常,有的花转成json输出到页面

 // if(true){
// String errorResultLocation = ajaxAction.getErrorResultLocation();
// String exceptionMessage =
// invocation.getStack().findString("exception.message");
// exceptionMessage = exceptionMessage.replaceAll("\r", " ");
// exceptionMessage = exceptionMessage.replaceAll("\n", " ");
// exceptionMessage = exceptionMessage.replaceAll("\t", " ");
// responseData = getFailureData(null, exceptionMessage);
// }

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

  1. Struts2自定义Result处理JSON

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

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

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

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

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

  4. struts2自定义转换器

    Struts2自定义类型转换器分为局部类型转换器和全局类型转换器 (1)局部类型转换器 如果页面传来一个参数reg.action?birthday=2010-11-12到后台action,然后属性用d ...

  5. struts2自定义拦截器 设置session并跳转

    实例功能:当用户登陆后,session超时后则返回到登陆页面重新登陆. 为了更好的实现此功能我们先将session失效时间设置的小点,这里我们设置成1分钟 修改web.xml view plainco ...

  6. struts2 自定义校验规则

    自定义校验规则:(了解) 在Struts2自定义校验规则: 1.实现一个Validator 接口. 2.一般开发中继承ValidatorSupport 或者 FieldValidatorSupport ...

  7. Struts2自定义类型转换,和处理类型转换错误

    Struts2自定义类型转换: 从前台接受到的类型全部是字符串,Struts2自带的一些基本类型转换有时不能满足我们的特别需要,如:日期字符串输入格式,还有一些自定义的类,直接传到后台,我们需要一些自 ...

  8. Struts2 中result type属性说明

    Struts2 中result type属性说明 首先看一下在struts-default.xml中对于result-type的定义: <result-types><result-t ...

  9. Struts2之Result详解

    上一篇我们把Struts2中的Action接收参数的内容为大家介绍了,本篇我们就一起来简单学习一下Action的4种Result type类型,分为:dispatcher(服务端页面跳转):redir ...

随机推荐

  1. 【转】【SSE】基于SSE指令集的程序设计简介

    基于SSE指令集的程序设计简介 作者:Alex Farber 出处:http://www.codeproject.com/cpp/sseintro.asp SSE技术简介 Intel公司的单指令多数据 ...

  2. 【Windows phone 8】欢迎引导页面02

    [目标]前一篇文章已经实现了图片的切换,这里需要限制pivot的循环滚动. [思路]通过手势事件,对第一张,最后一张图片处加以限制 [前台] 在pivot处加上 <toolkit:Gesture ...

  3. Discuz 取各排行榜数据

    取论坛指定版块帖子或回复(first=1 就是帖子的1楼, 如果=0 就是调用回复,fid=62 是论坛版块号): SELECT * FROM discuzx.pre_forum_post where ...

  4. webpack+react+redux+es6

    一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...

  5. 可以这样去理解group by和聚合函数(转)

    http://www.cnblogs.com/wuguanglei/p/4229938.html 写在前面的话:用了好久group by,今天早上一觉醒来,突然感觉group by好陌生,总有个筋别不 ...

  6. [vim]的关键字补全

    除了complete关键字补全,所有补全相关命令都以CTRL-X开始,然后再接与补全类型相关的命令.CTRL-N与CTRL-P在找的的内容中选择的通用的命令,上下选择用的,CTRL-E则是取消选择.( ...

  7. 客户端禁用cookies后session是否还起效果

    设置session和cookies的代码(webform1.aspx) if (txtName.Text == "wlzcool") { Session["uid&quo ...

  8. Jenkins问题汇总

    1.在jenkins里使用shell,如果shell起子进程会被jenkins强制杀掉的解决方法. http://scmbob.org/start-process-in-jenkins.html

  9. [转载]Java应用程序中的内存泄漏及内存管理

    近期发现测试的项目中有JAVA内存泄露的现象.虽然JAVA有垃圾回收的机制,但是如果不及时释放引用就会发生内存泄露现象.在实际工作中我们使用Jprofiler调用java自带的 jmap来做检测还是很 ...

  10. Xamarin 的 MVVM 之 Caliburn.Micro

    约定 Caliburn.Micro 以下简称 CMXamarin.Form 以下简称 XF 摘要CM 当前已释出 3.0 beta 版https://github.com/Caliburn-Micro ...