Struts2 AJAX请求 Session失效处理
在Struts应用中,我们发出的请求都会经过 相应的拦截器进行相关处理,一般都会有一个用户登录拦截(Session失效拦截);一般请求的话,如果Session失效时,我们会跳到登录页面,可是如果我们采用AJAX请求时,将会返回登录页面的HTML代码,这肯定不是我们想要的,那么我们如何解决呢?请看以下步骤:
一、建立拦截器
package com.xxx.planeap.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.xxx.common.contants.ConstantsKey; import com.xxx.common.contants.SessionKey; import com.xxx.planeap.domain.User; import com.xxx.planeap.security.SecurityContextUtil; /** * * @author Goma [email protected] * @version v1.0 * @since 2012-05-31 * */ public class SecurityInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(SecurityInterceptor.class); @Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub String className = invocation.getAction().getClass().getName(); String action = className.substring(className.lastIndexOf(".")+1,className.length()); String actionName = invocation.getProxy().getActionName(); String result; HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String type = request.getHeader("X-Requested-With"); User user = (User) ActionContext.getContext().getSession().get(SessionKey.CURRENT_USER); if (user == null) { logger.debug("SECURITY CHECKED: NEED TO LOGIN"); if ("XMLHttpRequest".equalsIgnoreCase(type)) {// AJAX REQUEST PROCESS response.setHeader("sessionstatus", ConstantsKey.MSG_TIME_OUT); result = null; } else {// NORMAL REQUEST PROCESS result = ActionSupport.LOGIN; } } else { logger.debug("SECURITY CHECKED: USER HAS LOGINED"); SecurityContextUtil.setCurrentUser(user); boolean hanPerm = SecurityContextUtil.hasPerm(action, actionName); logger.debug("SECURITY CHECKED: PERMISSION---"+action+"."+actionName+"="+hanPerm); result = invocation.invoke(); } return result; } }
二、定义全局AJAX请求结束处理方法
//全局的AJAX访问,处理AJAX清求时SESSION超时 $.ajaxSetup({ contentType:"application/x-www-form-urlencoded;charset=utf-8", complete:function(XMLHttpRequest,textStatus){ //通过XMLHttpRequest取得响应头,sessionstatus var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus"); if(sessionstatus=="timeout"){ //这里怎么处理在你,这里跳转的登录页面 window.location.replace(PlanEap.getActionURI("login")); } } });
相关推荐
houmenghu 2020-11-17
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
思君夜未眠 2020-08-25
取个好名字真难 2020-08-06
歆萌 2020-08-03
阳光之吻 2020-08-03
婷婷小屋 2020-07-28
solarspot 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06