判断用户session 是否过期,如果过期,让用户重新登录
1、在web.xml配置:
WmsFilter com.test.wms.filter.WmsFilter true WmsFilter /mgr/*/*基于请求路径过滤*/2、对应过滤器代码:
public class WmsFilter implements Filter {
// 日志
Logger logger = LoggerFactory.getLogger(WmsFilter.class);
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
throws IOException, ServletException {
if (!(sreq instanceof HttpServletRequest) || !(sresp instanceof HttpServletResponse)) {
throw new ServletException(“OncePerRequestFilter just supports HTTP requests”);
}
HttpServletRequest httpRequest = (HttpServletRequest) sreq;
HttpServletResponse httpResponse = (HttpServletResponse) sresp;
httpResponse.setHeader(“Cache-Control”,“no-cache”);
httpResponse.setHeader(“Pragma”,“no-cache”);
httpResponse.setDateHeader (“Expires”, -1);
httpResponse.setHeader(“P3P”,“CP=CAO PSA OUR”);
HttpSession session = httpRequest.getSession();
if(!httpResponse.isCommitted()){
if(session != null){
Object object = session.getAttribute(“userName”);
String userName = object == null ? null : (String) object;
if (userName == null) {
boolean isAjaxRequest = isAjaxRequest(httpRequest);
if (isAjaxRequest) {
httpResponse.sendError(HttpStatus.UNAUTHORIZED.value(), “您已经太长时间没有操作,请刷新页面”);
}
httpResponse.sendRedirect("/wms/index.jsp");
}
}else{
httpResponse.sendRedirect("/wms/index.jsp");
}
}
chain.doFilter(sreq, sresp);
}
/**
- 判断是否为Ajax请求
- @param request
-
HttpServletRequest
- @return 是true, 否false
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
return (request.getHeader(“X-Requested-With”) != null
&& “XMLHttpRequest”.equals(request.getHeader(“X-Requested-With”).toString()));
}
public void init(FilterConfig config) throws ServletException {
}
}
上一篇: css:显示文本省略号