在Struts应用中,我们发出的请求都会经过 相应的拦截器进行相关处理,一般都会有一个用户登录拦截(Session失效拦截);一般请求的话,如果Session失效时,我们会跳到登录页面,可是如果我们采用AJAX请求时,将会返回登录页面的HTML代码,这肯定不是我们想要的,那么我们如何解决呢?请看以下步骤:
一、建立拦截器
Java代码
packagecom.xxx.planeap.interceptor;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.log4j.Logger;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionInvocation;
importcom.opensymphony.xwork2.ActionSupport;
importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;
importcom.xxx.common.contants.ConstantsKey;
importcom.xxx.common.contants.SessionKey;
importcom.xxx.planeap.domain.User;
importcom.xxx.planeap.security.SecurityContextUtil;
/**
*
*@authorGomaOMA1989@YEAH.NET
*@versionv1.0
*@since2012-05-31
*
*/
publicclassSecurityInterceptorextendsAbstractInterceptor{
privatestaticfinallongserialVersionUID=1L;
privateLoggerlogger=Logger.getLogger(SecurityInterceptor.class);
@Override
publicStringintercept(ActionInvocationinvocation)throwsException{
//TODOAuto-generatedmethodstub
StringclassName=invocation.getAction().getClass().getName();
Stringaction=className.substring(className.lastIndexOf(".")+1,className.length());
StringactionName=invocation.getProxy().getActionName();
Stringresult;
HttpServletRequestrequest=ServletActionContext.getRequest();
HttpServletResponseresponse=ServletActionContext.getResponse();
Stringtype=request.getHeader("X-Requested-With");
Useruser=(User)ActionContext.getContext().getSession().get(SessionKey.CURRENT_USER);
if(user==null){
logger.debug("SECURITYCHECKED:NEEDTOLOGIN");
if("XMLHttpRequest".equalsIgnoreCase(type)){//AJAXREQUESTPROCESS
response.setHeader("sessionstatus",ConstantsKey.MSG_TIME_OUT);
result=null;
}else{//NORMALREQUESTPROCESS
result=ActionSupport.LOGIN;
}
}else{
logger.debug("SECURITYCHECKED:USERHASLOGINED");
SecurityContextUtil.setCurrentUser(user);
booleanhanPerm=SecurityContextUtil.hasPerm(action,actionName);
logger.debug("SECURITYCHECKED:PERMISSION---"+action+"."+actionName+"="+hanPerm);
result=invocation.invoke();
}
returnresult;
}
}
二、定义全局AJAX请求结束处理方法
Js代码
//全局的AJAX访问,处理AJAX清求时SESSION超时
$.ajaxSetup({
contentType:"application/x-www-form-urlencoded;charset=utf-8",
complete:function(XMLHttpRequest,textStatus){
//通过XMLHttpRequest取得响应头,sessionstatus
varsessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus");
if(sessionstatus=="timeout"){
window.location.replace(PlanEap.getActionURI("login"));
}
}
});