Filter登录拦截
-
继承
Filter
接口并实现doFilter()
方法public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String uri = request.getRequestURI(); System.out.println("uri: " + uri); System.out.println("uri.indexOf: " + uri.indexOf("login.do")); if (user == null && uri.indexOf("login.do") == -1) { response.sendRedirect(request.getContextPath() + "../login.jsp"); } else { filterChain.doFilter(request, response); } } @Override public void destroy() { } }
-
在
web.xml
中注册并映射Filter
<filter> <filter-name>loginFilter</filter-name> <filter-class>com.llanero.Filter.LoginFilter</filter-class