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 <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. */ 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中的簡單配置如下:
<!-- Char encoding --> <filter > < filter-name> characterFilter </filter-name > < filter-class> space.ifei.wxchat.sys.CharacterFilter </filter-class > <!-- <async-supported>true</async-supported> --> <!-- <init- param> --> <!-- <param-name>XXX</param-name> --> <!-- <param-value>QQQ</param-value> --> <!-- </init- param> --> </filter > <filter-mapping > <filter-name> characterFilter </filter-name > <!-- 同一個Filter,Filter的名字必須一致 --> <url-pattern> /* </url-pattern > <!-- Filter生效的 url規則,可以使用通配符 --> <!-- <dispatcher>REQUEST</dispatcher> --> <!-- <dispatcher>FORWARD</dispatcher> --> </filter-mapping >
其中:
“async-supported ”設置Servlet是否開啟異步支持,默認不開啟,詳細見:
http://www.ibm.com/developerworks/cn/java/j-lo-servlet30/
“init- param ”設置自定義Filter里面屬性的值;
“dispatcher ”設置到達servlet的方式,方式有4種:REQUEST,FORWARD,INCLUDE,ERROR.
需要注意的是:在一個Web程序中可以配置多個Filter,Filter的執行順序要分先后的