Struts2 自定义Result
注意:我只要是解决自定义返回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的更多相关文章
- Struts2自定义Result处理JSON
以前在采用Struts2开发的项目中,对JSON的处理一直都在Action里处理的,在Action中直接Response,最近研读了一下Struts2的源码,发现了一个更加优雅的解决办法,自己定义一个 ...
- Struts2 配置文件result的name属性和type属性
Struts2 配置文件result的name属性和type属性:Name属性SUCCESS:Action正确的执行完成,返回相应的视图,success是 name属性的默认值: NONE:表示Act ...
- Struts2自定义拦截器Interceptor以及拦截器登录实例
1.在Struts2自定义拦截器有三种方式: -->实现Interceptor接口 public class QLInterceptorAction implements Interceptor ...
- struts2自定义转换器
Struts2自定义类型转换器分为局部类型转换器和全局类型转换器 (1)局部类型转换器 如果页面传来一个参数reg.action?birthday=2010-11-12到后台action,然后属性用d ...
- struts2自定义拦截器 设置session并跳转
实例功能:当用户登陆后,session超时后则返回到登陆页面重新登陆. 为了更好的实现此功能我们先将session失效时间设置的小点,这里我们设置成1分钟 修改web.xml view plainco ...
- struts2 自定义校验规则
自定义校验规则:(了解) 在Struts2自定义校验规则: 1.实现一个Validator 接口. 2.一般开发中继承ValidatorSupport 或者 FieldValidatorSupport ...
- Struts2自定义类型转换,和处理类型转换错误
Struts2自定义类型转换: 从前台接受到的类型全部是字符串,Struts2自带的一些基本类型转换有时不能满足我们的特别需要,如:日期字符串输入格式,还有一些自定义的类,直接传到后台,我们需要一些自 ...
- Struts2 中result type属性说明
Struts2 中result type属性说明 首先看一下在struts-default.xml中对于result-type的定义: <result-types><result-t ...
- Struts2之Result详解
上一篇我们把Struts2中的Action接收参数的内容为大家介绍了,本篇我们就一起来简单学习一下Action的4种Result type类型,分为:dispatcher(服务端页面跳转):redir ...
随机推荐
- WP老杨解迷:如何营造让人花钱的游戏
游戏是最好做也是最不好做的项目,游戏的好坏现在都是直接从数据来说话,Windows Phone的游戏应用同样不可能逃出这个行业准则,要说在市场里做的好,那就直接拿数据来说,几乎没人会去在乎游戏到底传达 ...
- Linux 网络编程九(select应用--大并发处理)
//网络编程服务端 /* * 备注:因为客户端代码.辅助方法代码和epoll相同,所以select只展示服务器端代码 */ #include <stdio.h> #include < ...
- PC网站应用接入微信登录
参考文档: https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&ve ...
- 社交网站好友储存设计和实现(PHP+MySQL)
最近手头的一个网站新增社交功能,用户可以互加好友. 通常,对好友列表设计是新增一个好友,就往好友列表新增一行,当要查询一个用户好友 SELECT * FROM WHERE userid="1 ...
- Eclipse系列: 在Eclipse中用TODO标签管理任务(Task)(ZZ)
Elipse为Java项目的时候,有一个很人性化的"任务管理"功能,利用这个功能可以方便地将项目中一些需要处理的任务记录下来.先来看看"任务管理"是怎么使用的吧 ...
- [CareerCup] 13.1 Print Last K Lines 打印最后K行
13.1 Write a method to print the last K lines of an input file using C++. 这道题让我们用C++来打印一个输入文本的最后K行,最 ...
- 20145215《Java程序设计》第6周学习总结
20145215<Java程序设计>第六周学习总结 教材学习内容总结 输入/输出 InputStream与OutputStream 从应用程序角度来看,如果要将数据从来源取出,可以使用输入 ...
- 查询一个ID出现2种结果的情况
项目中书籍分个人和机构,分属不同的表 所以有的时候ID是一样的,那么只根据ID查询书籍就会存在ID=xxx的既有个人又有机构,而通常我们可能只需要一个,多的没做区分就出问题了! 所以数据统一做查询的时 ...
- Linux下线程池的理解与简单实现
首先,线程池是什么?顾名思义,就是把一堆开辟好的线程放在一个池子里统一管理,就是一个线程池. 其次,为什么要用线程池,难道来一个请求给它申请一个线程,请求处理完了释放线程不行么?也行,但是如果创建线程 ...
- 【MyEclipse 2015】 逆向破解实录系列【1】(纯研究)
声明 My Eclipse 2015 程序版权为Genuitec, L.L.C所有. My Eclipse 2015 的注册码.激活码等授权为Genuitec, L.L.C及其付费用户所有. 本文只从 ...