1. 程式人生 > >ajax Session失效如何跳轉到登入頁面

ajax Session失效如何跳轉到登入頁面

一、建立攔截器

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;

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"));

}

}

});