java Servlet Filter 拦截Ajax请求,统一处理session超时的问题
本站寻求有缘人接手,详细了解请联系站长QQ1493399855
后台增加filter,注意不要把druid也屏蔽了
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 org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject;import cn.zsmy.constant.Constant; import cn.zsmy.entity.User;/** * session超时过滤 * * @date 2016-10-20*/ public class SessionFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; //只过滤了ajax请求时session超时if (httpServletRequest.getHeader("x-requested-with") != null && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { Subject subject = SecurityUtils.getSubject();User user = (User) subject.getPrincipal();if(user == null){Constant.MY_LOG.debug("filter:sessionstatus timeout!");//如果是ajax请求响应头会有,x-requested-with httpServletResponse.setHeader("sessionstatus", "timeout");//在响应头设置session状态 return; }} chain.doFilter(request, response); } @Override public void destroy() { } }