Filter是Servlet规范中的一个高级特性,和Servlet不同的是,他们不处理客户端请求,只用于对request,response进行修改;
如果要自己实现一个自定义的Filter必须实现javax.servlet.Filter接口,接口中有三个方法:
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.
* @since Servlet 2.3
*/
public interface Filter {
/**
* Called by the web container to indicate to a filter that it is
* being placed into service.
*/
public void init(FilterConfig filterConfig ) throws ServletException;
/**
* The doFilter
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.
*/
public void doFilter(ServletRequest request , ServletResponse response ,
FilterChain chain )
throws IOException, ServletException;
/**
* Called by the web container to indicate to a filter that it is being
* taken out of service.
*/
public void destroy();
}
三个方法反应了Filter的生命周期,其中init(),destory()方法只在Web程序加载或者卸载的时候调用,doFilter()方法每次请求都会调用。
另外,Filter在web.xml中的简单配置如下:
< filter-name> characterFilter
< filter-class> space.ifei.wxchat.sys.CharacterFilter
characterFilter
/*
其中:
“init- param ”设置自定义Filter里面属性的值;
“dispatcher ”设置到达servlet的方式,方式有4种:REQUEST,FORWARD,INCLUDE,ERROR.
需要注意的是:在一个Web程序中可以配置多个Filter,Filter的执行顺序要分先后的