background image

3 import java.io.*;
4 public class TimeTrackFilter implements Filter {
5      private FilterConfig filterConfig = null;
6      public void init(FilterConfig filterConfig)
7         throws ServletException {
8         this.filterConfig = filterConfig;
9      }
10      public void destroy() {
11         this.filterConfig = null;
12      }
13      public void doFilter( ServletRequest request,
14         ServletResponse response, FilterChain chain )
15         throws IOException, ServletException {
16         Date startTime, endTime;
17         double totalTime;
18         startTime = new Date();
19         // Forward the request to the next resource in the chain
20         chain.doFilter(request, wrapper);
21         // -- Process the response -- \\
22         // Calculate the difference between the start time and end time
23         endTime = new Date();
24         totalTime = endTime.getTime() - startTime.getTime();
25         totalTime = totalTime / 1000; //Convert from milliseconds to seconds
26         StringWriter sw = new StringWriter();
27         PrintWriter writer = new PrintWriter(sw);
28         writer.println();
29         writer.println("===============");
30         writer.println("Total elapsed time is: " + totalTime + " seconds." );
31         writer.println("===============");
32         // Log the resulting string
33         writer.flush();
34         filterConfig.getServletContext().
35            log(sw.getBuffer().toString());
36      }
37 }
38
 
  这个过滤器的生命周期很简单,不管怎样,我们还是研究一下它吧:
  初始化

 

  当容器第一次加载该过滤器时, init() 方法将被调用。该类在这个方法中包含了一个

 

指向 FilterConfig 对象的引用。我们的过滤器实际上并不需要这样做,因为其中没有使
用初始化信息,这里只是出于演示的目的。