摘自http://zhangjunhd.blog.51cto.com/113473/20629/
1Servlet過濾器
1.1 什么是過濾器
過濾器是一個程序,它先于與之相關(guān)的servletJSP頁面運行在服務器上。過濾器可附加到一個或多個servletJSP頁面上,并且可以檢查進入這些資源的請求信息。在這之后,過濾器可以作如下的選擇:
①以常規(guī)的方式調(diào)用資源(即,調(diào)用servletJSP頁面)。
②利用修改過的請求信息調(diào)用資源。
③調(diào)用資源,但在發(fā)送響應到客戶機前對其進行修改。
④阻止該資源調(diào)用,代之以轉(zhuǎn)到其他的資源,返回一個特定的狀態(tài)代碼或生成替換輸出。
1.2 Servlet過濾器的基本原理
Servlet作為過濾器使用時,它可以對客戶的請求進行處理。處理完成后,它會交給下一個過濾器處理,這樣,客戶的請求在過濾鏈里逐個處理,直到請求發(fā)送到目標為止。例如,某網(wǎng)站里有提交“修改的注冊信息”的網(wǎng)頁,當用戶填寫完修改信息并提交后,服務器在進行處理時需要做兩項工作:判斷客戶端的會話是否有效;對提交的數(shù)據(jù)進行統(tǒng)一編碼。這兩項工作可以在由兩個過濾器組成的過濾鏈里進行處理。當過濾器處理成功后,把提交的數(shù)據(jù)發(fā)送到最終目標;如果過濾器處理不成功,將把視圖派發(fā)到指定的錯誤頁面。
2Servlet過濾器開發(fā)步驟
開發(fā)Servlet過濾器的步驟如下:
①編寫實現(xiàn)Filter接口的Servlet類。
②在web.xml中配置Filter。
開發(fā)一個過濾器需要實現(xiàn)Filter接口,Filter接口定義了以下方法:
destory()由Web容器調(diào)用,初始化此Filter。
initFilterConfig filterConfig)由Web容器調(diào)用,初始化此Filter
doFilterServletRequest request,ServletResponse response,FilterChain chain)具體過濾處理代碼。
3.一個過濾器框架實例
SimpleFilter1.java
 1package com.zj.sample;
 2import java.io.IOException;
 3import javax.servlet.Filter;
 4import javax.servlet.FilterChain;
 5import javax.servlet.FilterConfig;
 6import javax.servlet.ServletException;
 7import javax.servlet.ServletRequest;
 8import javax.servlet.ServletResponse;
 9public class SimpleFilter1 implements Filter {
10@SuppressWarnings("unused")
11private FilterConfig filterConfig;
12public void init(FilterConfig config) throws ServletException {
13this.filterConfig = config;
14}

15public void doFilter(ServletRequest request, ServletResponse response,
16FilterChain chain) {
17try {
18System.out.println("Within SimpleFilter1:Filtering the Request");
19chain.doFilter(request, response);// 把處理發(fā)送到下一個過濾器
20System.out .println("Within SimpleFilter1:Filtering the Response");
21}
 catch (IOException ioe) {
22ioe.printStackTrace();
23}
 catch (ServletException se) {
24se.printStackTrace();
25}

26}

27public void destroy() {
28this.filterConfig = null;
29}

30}



SimpleFilter2.java

1package com.zj.sample;
2import java.io.IOException;
3import javax.servlet.Filter;
4import javax.servlet.FilterChain;
5import javax.servlet.FilterConfig;
6import javax.servlet.ServletException;
7import javax.servlet.ServletRequest;
8import javax.servlet.ServletResponse;
9
10public class SimpleFilter2 implements Filter {
11 @SuppressWarnings("unused")
12 private FilterConfig filterConfig;
13
14 public void init(FilterConfig config) throws ServletException {
15 this.filterConfig = config;
16 }

17
18 public void doFilter(ServletRequest request, ServletResponse response,
19 FilterChain chain) {
20 try {
21 System.out.println("Within SimpleFilter2:Filtering the Request");
22 chain.doFilter(request, response); // 把處理發(fā)送到下一個過濾器
23 System.out.println("Within SimpleFilter2:Filtering the Response");
24 }
catch (IOException ioe) {
25 ioe.printStackTrace();
26 }
catch (ServletException se) {
27 se.printStackTrace();
28 }

29 }

30
31 public void destroy() {
32 this.filterConfig = null;
33 }

34}

web.xml
1 <filter>
2 <filter-name>filter1</filter-name>
3 <filter-class>com.zj.sample.SimpleFilter1</filter-class>
4 </filter>
5 <filter-mapping>
6 <filter-name>filter1</filter-name>
7 <url-pattern>/*</url-pattern>//為所有的訪問做過濾
8 </filter-mapping>
9
10 <filter>
11 <filter-name>filter2</filter-name>
12 <filter-class>com.zj.sample.SimpleFilter2</filter-class>
13 </filter>
14 <filter-mapping>
15 <filter-name>filter2</filter-name>
16 <url-pattern>/*</url-pattern>//為所有的訪問做過濾
17 </filter-mapping>


打開web容器中任意頁面輸出結(jié)果:(注意過濾器執(zhí)行的請求/響應順序)
Within SimpleFilter1:Filtering the Request...
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...

4.報告過濾器
我們來試驗一個簡單的過濾器,只要調(diào)用相關(guān)的servletJSP頁面,它就打印一條消息到標準輸出。為實現(xiàn)此功能,在doFilter方法中執(zhí)行過濾行為。每當調(diào)用與這個過濾器相關(guān)的servletJSP頁面時,doFilter方法就生成一個打印輸出,此輸出列出請求主機和調(diào)用的URL。因為getRequestURL方法位于HttpServletRequest而不是ServletRequest中,所以把ServletRequest對象構(gòu)造為HttpServletRequest類型。我們改動一下章節(jié)3SimpleFilter1.java
 1package com.zj.sample;
 2import java.io.IOException;
 3import java.util.Date;
 4import javax.servlet.Filter;
 5import javax.servlet.FilterChain;
 6import javax.servlet.FilterConfig;
 7import javax.servlet.ServletException;
 8import javax.servlet.ServletRequest;
 9import javax.servlet.ServletResponse;
10import javax.servlet.http.HttpServletRequest;
11 
12public class SimpleFilter1 implements Filter {
13    @SuppressWarnings("unused")
14    private FilterConfig filterConfig;
15 
16    public void init(FilterConfig config) throws ServletException {
17       this.filterConfig = config;
18    }

19 
20    public void doFilter(ServletRequest request, ServletResponse response,
21           FilterChain chain) {
22       try {
23           System.out.println("Within SimpleFilter1:Filtering the Request");
24           HttpServletRequest req = (HttpServletRequest) request;
25           System.out.println(req.getRemoteHost() + " tried to access "
26                  + req.getRequestURL() + " on " + new Date() + ".");
27           chain.doFilter(request, response);
28           System.out.println("Within SimpleFilter1:Filtering the Response");
29       }
 catch (IOException ioe) {
30           ioe.printStackTrace();
31       }
 catch (ServletException se) {
32           se.printStackTrace();
33       }

34    }

35 
36    public void destroy() {
37       this.filterConfig = null;
38    }

39}


web.xml設(shè)置不變,同章節(jié)3。
 
測試:
輸入[url]http://localhost:8080/Test4Jsp/login.jsp[/url]
 
結(jié)果:
Within SimpleFilter1:Filtering the Request...
0:0:0:0:0:0:0:1 tried to access [url]http://localhost:8080/Test4Jsp/login.jsp[/url] on Sun Mar 04 17:01:37 CST 2007.
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...

5.訪問時的過濾器在過濾器中使用servlet初始化參數(shù))
下面利用init設(shè)定一個正常訪問時間范圍,對那些不在此時間段的訪問作出記錄。我們改動一下章節(jié)3的SimpleFilter2.java。

 1package com.zj.sample;
 2import java.io.IOException;
 3import java.text.DateFormat;
 4import java.util.Calendar;
 5import java.util.GregorianCalendar;
 6import javax.servlet.Filter;
 7import javax.servlet.FilterChain;
 8import javax.servlet.FilterConfig;
 9import javax.servlet.ServletContext;
10import javax.servlet.ServletException;
11import javax.servlet.ServletRequest;
12import javax.servlet.ServletResponse;
13import javax.servlet.http.HttpServletRequest;
14 
15public class SimpleFilter2 implements Filter {
16    @SuppressWarnings("unused")
17    private FilterConfig config;
18    private ServletContext context;
19    private int startTime, endTime;
20    private DateFormat formatter;
21 
22    public void init(FilterConfig config) throws ServletException {
23       this.config = config;
24       context = config.getServletContext();
25       formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
26              DateFormat.MEDIUM);
27       try {
28           startTime = Integer.parseInt(config.getInitParameter("startTime"));// web.xml
29           endTime = Integer.parseInt(config.getInitParameter("endTime"));// web.xml
30       }
 catch (NumberFormatException nfe) // Malformed or null
31           // Default: access at or after 10 p.m. but before 6 a.m. is
32           // considered unusual.
33           startTime = 22// 10:00 p.m.
34           endTime = 6// 6:00 a.m.
35       }

36    }

37 
38    public void doFilter(ServletRequest request, ServletResponse response,
39           FilterChain chain) {
40       try {
41           System.out.println("Within SimpleFilter2:Filtering the Request");
42           HttpServletRequest req = (HttpServletRequest) request;
43           GregorianCalendar calendar = new GregorianCalendar();
44           int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
45           if (isUnusualTime(currentTime, startTime, endTime)) {
46              context.log("WARNING: " + req.getRemoteHost() + " accessed "
47                     + req.getRequestURL() + " on "
48                     + formatter.format(calendar.getTime()));
49              // The log file is under <CATALINA_HOME>/logs.One log per day.
50           }

51           chain.doFilter(request, response);
52           System.out
53                  .println("Within SimpleFilter2:Filtering the Response");
54       }
 catch (IOException ioe) {
55           ioe.printStackTrace();
56       }
 catch (ServletException se) {
57           se.printStackTrace();
58       }

59    }

60 
61    public void destroy() {}
62 
63    // Is the current time between the start and end
64    // times that are marked as abnormal access times?
65    private boolean isUnusualTime(int currentTime, int startTime, int endTime) {
66       // If the start time is less than the end time (i.e.,
67       // they are two times on the same day), then the
68       // current time is considered unusual if it is
69       // between the start and end times.
70       if (startTime < endTime) {
71           return ((currentTime >= startTime) && (currentTime < endTime));
72       }

73       // If the start time is greater than or equal to the
74       // end time (i.e., the start time is on one day and
75       // the end time is on the next day), then the current
76       // time is considered unusual if it is NOT between
77       // the end and start times.
78       else {
79           return (!isUnusualTime(currentTime, endTime, startTime));
80       }

81    }

82}

 

web.xml設(shè)置不變。
關(guān)于Tomcat日志處理,這里補充介紹一下。config.getServletContext().log"log message")會將日志信息寫入<CATALINA_HOME>/logs文件夾下,文件名應該為localhost_log.2007-03-04.txt這樣的形式(按日期每天產(chǎn)生一個,第二天可以看見)。要得到這樣一個日志文件,應該在server.xml中有:

<Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>

參考資料
[1] Marty Halls ,ServletJSP權(quán)威指南,機械工業(yè)出版社
[2] 趙強,精通JSP編程,電子工業(yè)出版社

本文出自 “子 孑” 博客,請務必保留此出處http://zhangjunhd.blog.51cto.com/113473/20629