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的执行顺序要分先后的
 
 
 

转载于:https://www.cnblogs.com/mr-frank/p/5521218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值