Java Filter过滤器

一:过滤器简介

Filter也称之为过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
它主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理。使用Filter的完整流程:Filter对用户请求进行预处理,接着将请求交给Servlet进行处理并生成响应,最后Filter再对服务器响应进行后处理。


二:过滤器功能

在HttpServletRequest到达 Servlet 之前,拦截客户的HttpServletRequest 。根据需要检查HttpServletRequest,也可以修改HttpServletRequest 头和数据。
在HttpServletResponse到达客户端之前,拦截HttpServletResponse 。根据需要检查HttpServletResponse,也可以修改HttpServletResponse头和数据。



三:过滤器开发


点击(此处)折叠或打开

  1. public interface Filter {

  2.     /**
  3.     * Called by the web container to indicate to a filter that it is being placed into
  4.     * service. The servlet container calls the init method exactly once after instantiating the
  5.     * filter. The init method must complete successfully before the filter is asked to do any
  6.     * filtering work. <br><br>

  7.          * The web container cannot place the filter into service if the init method either<br>
  8.         * 1.Throws a ServletException <br>
  9.         * 2.Does not return within a time period defined by the web container
  10.     */
  11.     public void init(FilterConfig filterConfig) throws ServletException;
  12.     
  13.     
  14.     /**
  15.     * The <code>doFilter</code> method of the Filter is called by the container
  16.     * each time a request/response pair is passed through the chain due
  17.     * to a client request for a resource at the end of the chain. The FilterChain passed in to this
  18.     * method allows the Filter to pass on the request and response to the next entity in the
  19.     * chain.


  20.     * A typical implementation of this method would follow the following pattern:- <br>
  21.     * 1. Examine the request<br>
  22.     * 2. Optionally wrap the request object with a custom implementation to
  23.     * filter content or headers for input filtering <br>
  24.     * 3. Optionally wrap the response object with a custom implementation to
  25.     * filter content or headers for output filtering <br>
  26.     * 4. a) Either invoke the next entity in the chain using the FilterChain object (<code>chain.doFilter()</code>), <br>
  27.     ** 4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing<br>
  28.     ** 5. Directly set headers on the response after invocation of the next entity in the filter chain.
  29.     **/
  30.     public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException;

  31.     /**
  32.     * Called by the web container to indicate to a filter that it is being taken out of service. This
  33.     * method is only called once all threads within the filter's doFilter method have exited or after
  34.     * a timeout period has passed. After the web container calls this method, it will not call the
  35.     * doFilter method again on this instance of the filter. <br><br>
  36.     *
  37.          * This method gives the filter an opportunity to clean up any resources that are being held (for
  38.     * example, memory, file handles, threads) and make sure that any persistent state is synchronized
  39.     * with the filter's current state in memory.
  40.     */

  41.     public void destroy();


  42. }
Filter接口中有一个doFilter方法,当开发人员编写好Filter,并配置对哪个web资源进行拦截后,Web服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:

调用目标资源之前,让一段代码执行。 是否调用目标资源(即是否让用户访问web资源)。 web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。

在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。

web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。

Filter的生命周期
public void init(FilterConfig filterConfig) throws ServletException;//初始化
和我们编写的Servlet程序一样,Filter的创建和销毁由WEB服务器负责。 web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,读取web.xml配置,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作(filter对象只会创建一次,init方法也只会执行一次)。开发人员通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain CHAIN) throws IOException, ServletException;//拦截请求
这个方法完成实际的过滤操作。当客户请求访问与过滤器关联的URL的时候,Servlet过滤器将先执行doFilter方法。FilterChain参数用于访问后续过滤器。

public void destroy();//销毁
Filter对象创建后会驻留在内存,当web应用移除或服务器停止时才销毁。在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。
FilterConfig接口


用户在配置filter时,可以使用为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得以下内容:


STRING getFilterName();//得到filter的名称。 
STRING getInitParameter(STRING NAME);//返回在部署描述中指定名称的初始化参数的值。如果不存在返回null. 
Enumeration getInitParameterNames();//返回过滤器的所有初始化参数的名字的枚举集合。 
public ServletContext getServletContext();//返回Servlet上下文对象的引用。


四:过滤器实例

本实例的作用是使页面支持gzip压缩资源请求(Content-Encoding:gzip)

web.xml配置

点击(此处)折叠或打开

  1. <filter>
  2.         <filter-name>GzipJsFilter</filter-name>
  3.         <filter-class>com.gemdale.gmap.manager.web.filter.GzipJsFilter</filter-class>
  4.         <init-param>
  5.             <param-name>headers</param-name>
  6.             <param-value>Content-Encoding=gzip</param-value>
  7.         </init-param>
  8.     </filter>
  9.     <filter-mapping>
  10.         <filter-name>GzipJsFilter</filter-name>
  11.         <url-pattern>*.gzjs</url-pattern>
  12.     </filter-mapping>
代码:

点击(此处)折叠或打开

  1. public class GzipJsFilter implements Filter {
  2.     Map headers = new HashMap();

  3.     public void destroy() {
  4.     }

  5.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
  6.             throws IOException, ServletException {
  7.         if (req instanceof HttpServletRequest) {
  8.             doFilter((HttpServletRequest) req, (HttpServletResponse) res, chain);
  9.         }
  10.         else {
  11.             chain.doFilter(req, res);
  12.         }
  13.     }

  14.     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
  15.             throws IOException, ServletException {
  16.         request.setCharacterEncoding("UTF-8");
  17.         for (Iterator it = headers.entrySet().iterator(); it.hasNext();) {
  18.             Map.Entry entry = (Map.Entry) it.next();
  19.             response.addHeader((String) entry.getKey(), (String) entry.getValue());
  20.         }
  21.         chain.doFilter(request, response);
  22.     }

  23.     public void init(FilterConfig config) throws ServletException {
  24.         String headersStr = config.getInitParameter("headers");
  25.         String[] headers = headersStr.split(",");
  26.         for (int i = 0; i < headers.length; i++) {
  27.             String[] temp = headers[i].split("=");
  28.             this.headers.put(temp[0].trim(), temp[1].trim());
  29.         }
  30.     }
  31. }







来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28624388/viewspace-2129713/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28624388/viewspace-2129713/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值