注意:我只要是解决自定义返回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. 10Mybatis_mybatis和hibernate本质区别和应用场景

    hibernate:是一个标准的ORM框架(对象关系映射).入门门槛较高,不需要程序写sql语句,sql语句自动生产了. 对sql的优化比较困难. 应用场景:适用与需求变化不多的中小型项目中,比如后台 ...

  2. GitLab/Git在AndroidStudio上的使用(转)

    1.在AndroidStudio上的配置GitLab 1)首先先将gitlab上的开发项目clone到本地(可以使用命令行或者管理工具,具体操作在GitLab中已经涉及,这里不再赘述),然后导入到An ...

  3. winform listbox与textbox组合提示框 模糊查询

      private void listbox1_MouseClick(object sender, MouseEventArgs e)        {            textbox1.Vis ...

  4. UTF-8 带签名和不带签名的区别

    就和字面上一样,带签名的UTF-8文件比不带签名的,在文件开头的地方就多了几个16进制字符--[EF BB BF ],这9个字符就是"签名",这样做的好处是让文本处理工具或者浏览器 ...

  5. [转]C#使用Log4Net记录日志

    第一步:下载Log4Net 下载地址:http://logging.apache.org/log4net/download_log4net.cgi 把下载的  log4net-1.2.11-bin-n ...

  6. Chrome浏览器扩展开发系列之十四

    Chrome浏览器扩展开发系列之十四:本地消息机制Native messaging 时间:2015-10-08 16:17:59      阅读:1361      评论:0      收藏:0    ...

  7. 如何在Ubuntu 14.04中安装最新版Eclipse

    想必很多开发人员都知道,Ubuntu 软件源中提供的并不是最新版本的 Eclipse,本教程就教大家如何在 Ubuntu 14.04 中快速安装 Eclipse 官方发布的最新版本. 到目前为止,Ec ...

  8. 区间dp的典例

    区间dp, 属于dp的一种,顾名思义,便是对区间处理的dp,其中石子归并,括号匹配,整数划分最为典型. (1)石子归并 dp三要素:阶段,状态,决策. 首先我们从第i堆石子到第j堆石子合并所花费的最小 ...

  9. HBase入库调优

    本文章只针对“微型集群处理大数据”的场景. 场景描述: 硬件:5个节点,每个节点可用硬盘1块(700G.500G等).8核cpu,实验室环境(有时候还要跑其他程序跟你抢占资源),16G内存. 软件:h ...

  10. DateTime类常用技巧摘录

    //今天 DateTime.Now.Date.ToShortDateString(); //昨天,就是今天的日期减一 DateTime.Now.AddDays(-).ToShortDateString ...