1. 程式人生 > >filter 攔截ajax請求

filter 攔截ajax請求

lsi ride ava let .ajax end logger pretty ngs

1.filter
public class SessonFilter implements Filter { private static Logger log = LoggerFactory.getLogger(SessonFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { //empty implement } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); String uri = httpRequest.getRequestURI(); String ctxpath = httpRequest.getContextPath(); String userid = (String)session.getAttribute("userid"); if(uri.contains("/user/login") || uri.contains("/user/regPage") ){ chain.doFilter(request, response); }else{ if(userid == null){ String contextPath = httpRequest.getContextPath(); String redirect = contextPath ; //ajax session 過期處理 //1:判斷是否是ajax請求 if (httpRequest.getHeader("x-requested-with") != null && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("x-requested-with"))) { //向http頭添加 狀態 sessionstatus httpResponse.setHeader("sessionstatus","timeout"); httpResponse.setStatus(403); //向http頭添加登錄的url httpResponse.addHeader("loginPath", ctxpath); chain.doFilter(request, response); log.debug("ajax request"); return ; } httpResponse.sendRedirect(redirect); return; }else{ chain.doFilter(request, response); } } } @Override public void destroy() { //empty implement } }

2.核心代碼

//ajax session 過期處理
//1:判斷是否是ajax請求
if (httpRequest.getHeader("x-requested-with") != null 
                        && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("x-requested-with"))) {   
    //向http頭添加 狀態 sessionstatus
    httpResponse.setHeader("sessionstatus","timeout");
    httpResponse.setStatus(403);
    //向http頭添加登錄的url
    httpResponse.addHeader("loginPath", ctxpath);
    chain.doFilter(request, response);
    log.debug("ajax request");
    return ;
}
3.JS
//ajax完成時回調函數
$(document).ajaxComplete(function(event, xhr, settings) {
    //從http頭信息取出 在filter定義的sessionstatus,判斷是否是 timeout
    if(xhr.getResponseHeader("sessionstatus")=="timeout"){ 
        //從http頭信息取出登錄的url = loginPath
        if(xhr.getResponseHeader("loginPath")){
            alert("會話過期,請重新登陸!");
            //打會到登錄頁面
            window.location.replace(xhr.getResponseHeader("loginPath"));  
        }else{  
            alert("請求超時請重新登陸 !");  
        }  
    }  
}); 
 

filter 攔截ajax請求