利用Filter实现session拦截
1、在web.xml中配置
<!-- Session监听器 --> <filter> <filter-name>sessionValidateFilter</filter-name> <filter-class>cn.jxufe.core.filter.SessionValidateFilter</filter-class> </filter> <filter-mapping> <filter-name>sessionValidateFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping>
2、创建自定义过滤器类
public class SessionValidateFilter implements Filter { public void destroy() {} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); if ((session == null) || (session.getAttribute("username") == null)) { String PATH=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; response.sendRedirect(PATH+"login.jsp"); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException {} }
作者:何海洋
本博客内容主要以学习、研究和分享为主,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。