java Servlet Filter 拦截Ajax请求
/** * 版权:Copyright 2016-2016 AudaqueTech. Co. Ltd. All Rights Reserved. * 描述: * 创建人:赵巍 * 创建时间:2016年11月28日 * 修改人: * 修改时间: * 修改内容: */ package com.thinkgem.jeesite.common.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CustomFilter implements Filter { private final Logger logger = LoggerFactory.getLogger(getClass()); private String failureUrl; @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 userid = (String)session.getAttribute("userid"); Subject subject = SecurityUtils.getSubject(); /* if(uri.contains("/user/login") || uri.contains("/user/regPage") ){ chain.doFilter(request, response); }else{ */ if(subject.getPrincipals() == 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.sendError(518, "session timeout."); /*httpResponse.setStatus(403);*/ //向http头添加登录的url httpResponse.addHeader("loginPath", failureUrl); chain.doFilter(request, response); logger.debug("ajax request"); return ; } httpResponse.sendRedirect(redirect); return; }else{ chain.doFilter(request, response); } /*}*/ } @Override public void destroy() { //empty implement } public String getFailureUrl() { return failureUrl; } public void setFailureUrl(String failureUrl) { this.failureUrl = failureUrl; } }
$.ajax({ type: "get", url: $(this).attr("data-href"), success: function(data){ // }, complete: function(xhr,status){ var sessionStatus = xhr.getResponseHeader('sessionstatus'); if(sessionStatus == 'timeout') { top.location = "${ctx}"; return false; } } }); }