public interface Filter
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
(过滤器是一个对象,它对资源(servlet或静态内容)的请求执行过滤任务,或对资源的响应,或两者都执行过滤任务。)
Filters perform filtering in the
doFilter
method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.(滤波器采用doFilter方法 执行过滤。每个过滤器访问FilterConfig 对象获得它的初始化参数,并参考ServletContext它可以使用,例如,加载过滤任务所需要的资源。)
Filters are configured in the deployment descriptor of a web application.
(过滤器配置在Web应用程序的部署描述符中。)
Examples that have been identified for this design are:
- Authentication Filters ----身份认证过滤
- Logging and Auditing Filters ---日志和认证过滤
- Image conversion Filters ----图像转换过滤器
- Data compression Filters --数据压缩过滤器
- Encryption Filters ---加密过滤
- Tokenizing Filters
- Filters that trigger resource access events----触发资源访问事件的过滤器
- XSL/T filters
- Mime-type chain Filter MIME型链过滤器
Filter生命周期:
先执行Filter的构造方法
然后执行Filter的init方法 init(FilterConfig filterConfig)
执行Filter的doFilter方法,每次访问资源,只要匹配过滤的地址,就会调用。 doFilter()
执行Filter的destroy方法 void destroy()
FilterConfig类
FilterConfig类,一般有三个作用:
- 获取Filter在web.xml文件中配置的名称 ----filterConfig.getFilterName()
- 获取Filter在web.xml文件中配置的初始化参数 ---filterConfig.getFilterParameter("username")
- 通过FilterConfig类获取ServletContext对象实例 ---filterConfig.getServletContext();
FilterChain 过滤器链(重点****)
void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException,
Filter的拦截路径
精确匹配 比如: /xxx/xxx/xxx.jsp 或 /xxx/xxx/xxx.html 等
目录匹配 比如:
/abc/* 表示可以拦截abc目录下的所有资源,甚至是abc目录下的其他目录,
/* 表示访问 当前工程下所有资源
后缀名匹配 比如:*.jsp 表示拦截所有后缀为jsp文件资源