Filter入门实例

一、介绍

  Filter:Filter是Servlet的“加强版”,它主要用于对用户请求进行预处理,也可对HttpServletResponse进行后处理,是个典型的“处理链”。Filter也可以对用户请求产生响应,这一点与Servlet相同,但实际上很少会使用Filter向用户请求生成响应。

  使用Filter的完整流程是:Filter对用户请求进行预处理,接着将请求交给Servlet进行处理并生成响应,最后Filter再对服务器响应进行后处理

二、创建并使用Filter

  1、创建Filter处理类(必须实现javax.servlet.Filter接口)

  2、web.xml中配置Filter

例1:

// LogFilter.java负责拦截所有的用户请求,并将请求的信息记录在日志中。

 1 import java.io.IOException;
 2 import javax.servlet.Filter;
 3 import javax.servlet.FilterChain;
 4 import javax.servlet.FilterConfig;
 5 import javax.servlet.ServletContext;
 6 import javax.servlet.ServletException;
 7 import javax.servlet.ServletRequest;
 8 import javax.servlet.ServletResponse;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.annotation.WebFilter;
11 
12 @WebFilter(filterName="log"
13         ,urlPatterns={"/"})
14 //@WebFilter(filterName="log",urlPatterns="/*")
15 public class LogFilter implements Filter{
16 
17     //FilterConfig可用于访问Filter的配置信息
18     private FilterConfig config;
19     
20     //实现初始化方法
21     @Override
22     public void init(FilterConfig config) throws ServletException {
23         // TODO Auto-generated method stub
24         this.config = config;
25     }
26     
27     //实现销毁方法
28     @Override
29     public void destroy() {
30         // TODO Auto-generated method stub
31         config = null;
32     }
33     
34     //执行过滤的核心方法:该方法就是对每个请求及响应增加额外的处理
35     @Override
36     public void doFilter(ServletRequest request, ServletResponse response,
37             FilterChain chain) throws IOException, ServletException {
38         // TODO Auto-generated method stub
39         
40         // -----------下面代码用于对用户请求进行预处理----------------
41         long before = System.currentTimeMillis();
42         System.out.println("开始过滤。。。");
43         
44         //将请求转换为HttpServletRequest请求
45         HttpServletRequest hRequest = (HttpServletRequest)request;
46         //输出提示信息
47         System.out.println("Filter已经截取到用户请求的地址:" + hRequest.getServletPath());
48         
49         //Filter只是链式处理,请求依然放到目的地址
50         chain.doFilter(request, response);
51         
52         //下面代码用于对服务器响应做后处理
53         long after = System.currentTimeMillis();
54         //输出提示信息
55         System.out.println("过滤结束。。。");
56         //输出提示信息
57         System.out.println("请求被定位到" + hRequest.getRequestURI() + "  所花的时间:" + (after - before));
58     }
59 
60 }

 //web.xml配置

 1    <filter>
 2     <!--Filter的名字,相当于@WebFilter的urlPatterns属性-->
 3       <filter-name>log</filter-name>
 4       <filter-class>LogFilter</filter-class>
 5   </filter>
 6   <filter-mapping>
 7       <filter-name>log</filter-name>
 8     <!--Filter负责拦截的URL,相当于@WebFilter的filterName属性
 9         配置为/*表示该Filter会拦截所有用户请求-->
10       <url-pattern>/*</url-pattern>
11   </filter-mapping>

演示:

tomcat后台打印日志:

说明:

http://blog.csdn.net/huangcongjie/article/details/7377422 

http://www.oschina.net/question/106215_13779

过滤器的生命周期一般都要经过下面三个阶段:

 (1)初始化

当容器第一次加载该过滤器时,init() 方法将被调用。该类在这个方法中包含了一个指向 Filter Config 对象的引用。我们的过滤器实际上并不需要这样做,因为其中没有使用初始化信息,这里只是出于演示的目的。

 (2)过滤

过滤器的大多数时间都消耗在这里。doFilter方法被容器调用,同时传入分别指向这个请求/响应链中的 Servlet Request、Servlet Response 和 Filter Chain 对象的引用。然后过滤器就有机会处理请求,将处理任务传递给链中的下一个资源(通过调用 Filter Chain 对象引用上的 doFilter方法),之后在处理控制权返回该过滤器时处理响应。

 (2)析构

容器紧跟在垃圾收集之前调用 destroy()方法,以便能够执行任何必需的清理代码。

 关于chain.doFilter(request,response)
他的作用是将请求转发给过滤器链上下一个对象。这里的下一个指的是下一个filter,如果没有filter那就是你请求的资源。 一般filter都是一个链,web.xml 里面配置了几个就有几个。一个一个的连在一起 

request -> filter1 -> filter2 ->filter3 -> .... -> request resource.

 API说明:

javax.servlet 
Interface Filter


public interface Filter

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. 

Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

Filters are configured in the deployment descriptor of a web application

Examples that have been identified for this design are
1) Authentication Filters 
2) Logging and Auditing Filters 
3) Image conversion Filters 
4) Data compression Filters 
5) Encryption Filters 
6) Tokenizing Filters 
7) Filters that trigger resource access events 
8) XSL/T filters 
9) Mime-type chain Filter 

Since:
Servlet 2.3

 


 

Method Summary
 void destroy() 
          Called by the web container to indicate to a filter that it is being taken out of service.
 void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
          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.
 void init(FilterConfig filterConfig) 
          Called by the web container to indicate to a filter that it is being placed into service.

javax.servlet 
Interface FilterChain


public interface FilterChain

A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain.

Since:
Servlet 2.3
See Also:
Filter

 

Method Summary
 void doFilter(ServletRequest request, ServletResponse response) 
          Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

三、Filter的作用

  假设系统中有多个Servlet,这些Servlet都需要进行一些通用的处理:比如权限控制、记录日志等,这将导致在这些Servlet的service()方法中有部分代码是相同的——为了解决这种代码重复的问题,我们可以考虑把这些通用处理提取到Filter中完成。

 

  其它比如,(1)在Filter的doFilter里面设置request编码的字符集,从而避免每个JSP、Servlet都需要设置

       (2)验证用户是否登录,如果用户没有登录,系统直接跳转到登录页面

 

posted on 2013-12-15 14:50  gogoy  阅读(364)  评论(0编辑  收藏  举报

导航