1,java 代码中实现过滤器 通过实现import javax.servlet.Filter;接口
2,web.xml 配置需要通过过滤器的请求
package com.mvc.filter.user; 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; public class UserFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { HttpSession session = ((HttpServletRequest) req).getSession(); HttpServletRequest request = (HttpServletRequest) req; String reqPath = request.getRequestURI(); if (reqPath.contains("login.do")) { fc.doFilter(req, resp); } else { if (session.getAttribute("loginUser") != null) { fc.doFilter(req, resp); } else { HttpServletResponse response = (HttpServletResponse) resp; response.sendRedirect("/login.jsp"); } } } @Override public void init(FilterConfig arg0) throws ServletException { } }
<filter> <filter-name>userFilter</filter-name> <filter-class>com.mvc.filter.user.UserFilter</filter-class> </filter> <filter-mapping> <filter-name>userFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>