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 ...
随机推荐
- 研:手势与眼动相结合-手势SDK的整合
Leap提供了SDK.但是整合有很多的问题,写博客记录一下: 写一个类:SampleListener.cpp以及头文件SampleListener.h. 这里主要碰到的问题是找不到以及冲突问题: 这里 ...
- Linux 守护进程一
守护进程是一个后台进程,它无需用户输入就能运行,经常是提供某种服务. LInux作为服务器,主要的进程也都是为系统或用户提供后台服务功能. 常见的守护进程有Web服务器.邮件服务器以及数据库服务器等等 ...
- Unity 协程Coroutine综合测试
using UnityEngine; using System.Collections; using System.Text; public class rotCube : MonoBehaviour ...
- libevent+bufferevent总结
libevent+bufferevent总结 1 学习参考网址 libevent学习网址:http://blog.csdn.net/feitianxuxue/article/details/93725 ...
- 从0开始学Java——JSP&Servlet——Tomcat和Apache的区别
从<JSP & Servlet 学习笔记>的第一章,了解到web容器:“Web容器是Servlet/jsp唯一认得的http服务器”. 在Java中,容器的类型有多种,这里要说的是 ...
- [CareerCup] 2.3 Delete Node in a Linked List 删除链表的节点
2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access ...
- MyBatis与Hibernate对比
一.相同点 都屏蔽 jdbc api 的底层访问细节,使用我们不用与 jdbc api 打交道,就可以访问数据. jdbc api 编程流程固定,还将 sql 语句与 java 代码混杂在了一起,经常 ...
- 证书与keytool
证书的来源与使用: 对数据进行签名是我们在网络中最常见的安全操作.签名有双重作用,作用一就是保证数据的完整性,证明数据并非伪造,而且在传输的过程中没有被篡改,作用二就是防止数据的发布者否认其发布了该数 ...
- 开始开发HoloLens应用吧 Start Developing HoloLens Apps Today
在经历数个月的期待与等待后,终于拿到了预订的 HoloLens 开发者版本套件.经过一个月的学习和研究,对于HoloLens开发有了更浓厚的兴趣. 根据积累的经验,特录制了一节HoloLens开发教程 ...
- WCF Data Service 使用小结 (一)—— 了解OData协议
最近做了一个小项目,其中用到了 WCF Data Service,之前是叫 ADO.NET Data Service 的.关于WCF Data Service,博客园里的介绍并不多,但它确实是个很好的 ...