注意:我只要是解决自定义返回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. IEnumerable和IEnumerator 详解 (转)

    原文链接:http://blog.csdn.net/byondocean/article/details/6871881 参考链接:http://www.cnblogs.com/hsapphire/a ...

  2. 《JAVA与模式》之适配器模式(转)

    在阎宏博士的<JAVA与模式>一书中开头是这样描述适配器(Adapter)模式的: 适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能 ...

  3. [py]编码 Unicode utf-8

    什么是字符集 在介绍字符集之前,我们先了解下为什么要有字符集.我们在计算机屏幕上看到的是实体化的文字,而在计算机存储介质中存放的实际是二进制的比特流.那么在这两者之间的转换规则就需要一个统一的标准,否 ...

  4. C语言 结构体中的成员域偏移量

    //C语言中结构体中的成员域偏移量 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> # ...

  5. C++的CreateThread实例

    function CreateThread(  lpThreadAttributes: Pointer;           {安全设置}  dwStackSize: DWORD;           ...

  6. python数字图像处理(4):图像数据类型及颜色空间转换

    一.图像数据类型及转换 在skimage中,一张图片就是一个简单的numpy数组,数组的数据类型有很多种,相互之间也可以转换.这些数据类型及取值范围如下表所示: Data type Range uin ...

  7. 在opencv3中实现机器学习算法之:利用最近邻算法(knn)实现手写数字分类

    手写数字digits分类,这可是深度学习算法的入门练习.而且还有专门的手写数字MINIST库.opencv提供了一张手写数字图片给我们,先来看看 这是一张密密麻麻的手写数字图:图片大小为1000*20 ...

  8. 20135306黄韧[2.72 2.77 3.70](http://i.cnblogs.com/EditPosts.aspx?opt=1)

    2.72 A.size_t是无符号整数,因此左边都会先转换为无符号整数,它肯定是大于等于0的. B.判断条件改为 if(maxbytes > 0 && maxbytes > ...

  9. log4j使用教程

    日志是应用软件中不可缺少的部分,Apache的开源项目 Log4j 是一个功能强大的日志组件,提供方便的日志记录. 在官网:https://logging.apache.org/ ,点击 进入后,可以 ...

  10. IOS开发之——意见反馈UITextView的使用+不能输入字符输入

    @interface DMFeedbackViewController ()<UITextViewDelegate,UIAlertViewDelegate>@property (nonat ...