Java中的Filter详解 --基础篇

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的执行顺序要分先后的
 
 
 
posted @ 2016-05-23 19:50  阿飞肥了  阅读(3637)  评论(0编辑  收藏  举报