3在Servlet被调用之后检查Response对象,修改Response Header和Response内容。Servlet过滤器负责过滤的Web组件可以是Servlet、JSP或HTML文件。
4 filter 的执行流程
5 Filter的定义 需要实现Filter接口,
init(FilterConfig):这是Servlet过滤器的初始化方法,Servlet容器创建Servlet过滤器实例后将调用这个方法。在这个方法中可以读取web.xml 文件中Servlet过滤器的初始化参数
•doFilter(ServletRequest, ServletResponse,FilterChain):
这个方法完成实际的过滤操作。当客户请求访问与过滤器关联的URL时,Servlet容器将先调用过滤器的doFilter方法。FilterChain参数用于访问后续过滤器
•destroy():Servlet容器在销毁过滤器实例前调用该方法,在这个方法中可以释放Servlet
public class LoginFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest) arg0; HttpSession session=request.getSession(); User user=(User)session.getAttribute("user"); if (request.getRequestURI().endsWith("login.jsp")||request.getRequestURI().endsWith("Check")) { arg2.doFilter(arg0,arg1); System.out.println("if 1"); return; } else if (null==user) { request.getRequestDispatcher("filter/login.jsp").forward(arg0,arg1); System.out.println("if 2"); return; } else { arg2.doFilter(arg0,arg1); System.out.println("if 3"); } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
6 配置filter 在web.xml中配置
<filter> <filter-name>LoginFilter</filter-name> <filter-class>com.songxu.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
7 串联的Filter的执行流程
客户端提交请求后,执行F1中Code1 遇到doFilter 转向F2 执行,遇到dofiter转向后续,直到servlet返回,并依次进入F2,F1分别执行dofilter之后的代码片段 code2
测试代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("F1 before"); chain.doFilter(request,response); System.out.println("F1 after"); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("F2 before"); chain.doFilter(request,response); System.out.println("F2 after"); }