过滤器是指拦截请求,并对传给被请求资源的ServletRequest 或 ServletResponse 进行处理的一个对象。过滤器可以用于登录、加密和解密、会话检查等等。过滤器可以配置为拦截一个或多个资源。如果同一个资源或同一组资源中应用了多个过滤器,则调用顺序有显示显得比较重要,这时候就需要部署描述符(web.xml)来控制其先后顺序。
filter过滤器中使用的接口包括Filter、FilterConfig和FilterChain。每个接口中包含若干方法,接下来我们按照filter的生命周期来介绍接口及中间对应的方法。
过滤器类必须实现javax.servlet.Filter接口。这个接口为每个过滤器暴露3个生命周期方法,init、doFilter 和 destory。
package javax.servlet;
import java.io.IOException;
/**
* 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. <br>
* @since Servlet 2.3
*/
public interface Filter {
/**
* Called by the web container to indicate to a filter that it is being
* placed into service. The servlet container calls the init method exactly
* once after instantiating the filter. The init method must complete
* successfully before the filter is asked to do any filtering work. <br>
* <br>
* The web container cannot place the filter into service if the init method
* either<br>
* 1.Throws a ServletException <br>
* 2.Does not return within a time period defined by the web container
*/
public void init(FilterConfig filterConfig) throws ServletException;
/**
* The <code>doFilter</code> method of the Filter is called by the container
* each time a request/response pair is passed through the chain due to a
* client request for a resource at the end of the chain. The FilterChain
* passed in to this method allows the Filter to pass on the request and
* response to the next entity in the chain.
* <p>
* A typical implementation of this method would follow the following
* pattern:- <br>
* 1. Examine the request<br>
* 2. Optionally wrap the request object wi