分析LogFilter

 1 package lee;
 2 
 3 import javax.servlet.*;
 4 import javax.servlet.http.*;
 5 import javax.servlet.annotation.*;
 6 
 7 import java.io.*;
 8 
 9 /**
10  * Description:
11  * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
12  * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
13  * <br/>This program is protected by copyright laws.
14  * <br/>Program Name:
15  * <br/>Date:
16  * @author  Yeeku.H.Lee kongyeeku@163.com
17  * @version  1.0
18  */
19 
20 @WebFilter(filterName="log"
21     ,urlPatterns={"/*"})
22 public class LogFilter implements Filter
23 {
24     // FilterConfig可用于访问Filter的配置信息
25     private FilterConfig config;
26     // 实现初始化方法
27     public void init(FilterConfig config)
28     {
29         this.config = config;
30     }
31     // 实现销毁方法
32     public void destroy()
33     {
34         this.config = null;
35     }
36     // 执行过滤的核心方法
37     public void doFilter(ServletRequest request,
38         ServletResponse response, FilterChain chain)
39         throws IOException,ServletException
40     {
41         // ---------下面代码用于对用户请求执行预处理---------
42         // 获取ServletContext对象,用于记录日志
43         ServletContext context = this.config.getServletContext();
44         long before = System.currentTimeMillis();
45         System.out.println("开始过滤...");
46         // 将请求转换成HttpServletRequest请求
47         HttpServletRequest hrequest = (HttpServletRequest)request;
48         // 输出提示信息
49         System.out.println("Filter已经截获到用户的请求的地址: " +
50             hrequest.getServletPath());
51         // Filter只是链式处理,请求依然放行到目的地址
52         chain.doFilter(request, response);
53         // ---------下面代码用于对服务器响应执行后处理---------
54         long after = System.currentTimeMillis();
55         // 输出提示信息
56         System.out.println("过滤结束");
57         // 输出提示信息
58         System.out.println("请求被定位到" + hrequest.getRequestURI() +
59             "   所花的时间为: " + (after - before));
60     }
61 }
原文地址:https://www.cnblogs.com/shawlove/p/8917645.html