a)一个Web应用可以有0个或多个Filter,多个Filter的组合就是过滤器链 b)多个Filter的执行先后顺序,与web.xml文件中配置的顺序有关 c)chain.doFilter(request,response)具有二义性: >>如果有下一个Filter时,将请求转发给下一个Filter >>如果无下一个Filter时,将请求转发给Web资源(serlvet/jsp/html) d)可以将web资源中的一些公共代码,提取出来,放入Filter中
`<filter>
<filter-name>FilterDemo1</filter-name>
<filter-class>cn.web.servlet.filter.FilterDemo1</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>FilterDemo2</filter-name>
<filter-class>cn.web.servlet.filter.FilterDemo2</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
`
`import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write("欢迎学习Servlet下篇");
}
}`
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;
public class FilterDemo2 implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("第二个拦截器:Filter2");
//放行请求[调用]
chain.doFilter(request,response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}