session过期后自动跳转到登陆页

1、struts2.xml中添加拦截器配置

                        <!-- session拦截器 -->
			<interceptor name="sessionInterceptor" class="com.somnus.interceptor.base.SessionInterceptor" />
			<interceptor-stack name="sessionStack">
				<interceptor-ref name="encodingStack"></interceptor-ref>
				<interceptor-ref name="sessionInterceptor">
					<!-- doNotNeedSessionAndSecurity_ 开头的和doNotNeedSession_ 开头的方法不拦截 -->
					<param name="excludeMethods">doNotNeedSession_*,doNotNeedSessionAndSecurity_*,checkIsUnique</param>
				</interceptor-ref>
			</interceptor-stack>

2、新建SessionFilter类,实现Filter接口。

public class SessionInterceptor extends MethodFilterInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(SessionInterceptor.class);

	protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(ConfigUtil.getSessionInfoName());
		logger.info("进入session拦截器->访问路径为[" + request.getServletPath() + "]");
		if (sessionInfo == null) {
			String errMsg = "您还没有登录或登录已超时,请重新登录,然后再刷新本功能!";
			logger.info(errMsg);
			if (request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
				logger.info("进入session拦截器->----->异步请求----->");
				response.addHeader("sessionstatus", "timeOut");
			}
			return "noSession";
		}
		return actionInvocation.invoke();
	}

}


3、客户端JS,用于ajax请求session超时

对于jquery

<script type="text/javascript">
$(document).ajaxComplete(function(event, xhr, settings) {  
    if(xhr.getResponseHeader("sessionstatus")=="timeOut"){  
        if(xhr.getResponseHeader("loginPath")){
            alert("会话过期,请重新登陆!");
            window.location.replace(xhr.getResponseHeader("loginPath"));  
        }else{  
            alert("请求超时请重新登陆 !");  
        }  
    }  
});  
</script>


?

对于extjs4的ajax请求

Ext.data.Connection.on('requestcomplete', function (conn, response) {
	if (response && response.getResponseHeader){
		if (response.getResponseHeader('sessionstatus') == 'timeOut') {
			Ext.Msg.show({
				title: '信息',
				msg: '对不起,当前登录已过期,请重新登录!',
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.INFO,
				fn: function () {
					window.location.href = app.contextPath;
				}
			});
		}
	}
});


如果使某个ajax请求不受全局方法的影响,那么可以在使用$.ajax()方法时,将参数中的global设置为false,jquery代码如下:

$.ajax({
    url:"test.html",
    global:false//不触发全局ajax事件
})

?

你可能感兴趣的:(Ajax,session,异步,过期,登录页)