摘自
http://zhangjunhd.blog.51cto.com/113473/20629/
1.Servlet過(guò)濾器
1.1 什么是過(guò)濾器
過(guò)濾器是一個(gè)程序,它先于與之相關(guān)的servlet或JSP頁(yè)面運(yùn)行在服務(wù)器上。過(guò)濾器可附加到一個(gè)或多個(gè)servlet或JSP頁(yè)面上,并且可以檢查進(jìn)入這些資源的請(qǐng)求信息。在這之后,過(guò)濾器可以作如下的選擇:
①以常規(guī)的方式調(diào)用資源(即,調(diào)用servlet或JSP頁(yè)面)。
②利用修改過(guò)的請(qǐng)求信息調(diào)用資源。
③調(diào)用資源,但在發(fā)送響應(yīng)到客戶(hù)機(jī)前對(duì)其進(jìn)行修改。
④阻止該資源調(diào)用,代之以轉(zhuǎn)到其他的資源,返回一個(gè)特定的狀態(tài)代碼或生成替換輸出。
1.2 Servlet過(guò)濾器的基本原理
在Servlet作為過(guò)濾器使用時(shí),它可以對(duì)客戶(hù)的請(qǐng)求進(jìn)行處理。處理完成后,它會(huì)交給下一個(gè)過(guò)濾器處理,這樣,客戶(hù)的請(qǐng)求在過(guò)濾鏈里逐個(gè)處理,直到請(qǐng)求發(fā)送到目標(biāo)為止。例如,某網(wǎng)站里有提交“修改的注冊(cè)信息”的網(wǎng)頁(yè),當(dāng)用戶(hù)填寫(xiě)完修改信息并提交后,服務(wù)器在進(jìn)行處理時(shí)需要做兩項(xiàng)工作:判斷客戶(hù)端的會(huì)話是否有效;對(duì)提交的數(shù)據(jù)進(jìn)行統(tǒng)一編碼。這兩項(xiàng)工作可以在由兩個(gè)過(guò)濾器組成的過(guò)濾鏈里進(jìn)行處理。當(dāng)過(guò)濾器處理成功后,把提交的數(shù)據(jù)發(fā)送到最終目標(biāo);如果過(guò)濾器處理不成功,將把視圖派發(fā)到指定的錯(cuò)誤頁(yè)面。
2.Servlet過(guò)濾器開(kāi)發(fā)步驟
開(kāi)發(fā)Servlet過(guò)濾器的步驟如下:
①編寫(xiě)實(shí)現(xiàn)Filter接口的Servlet類(lèi)。
②在web.xml中配置Filter。
開(kāi)發(fā)一個(gè)過(guò)濾器需要實(shí)現(xiàn)Filter接口,Filter接口定義了以下方法:
①destory()由Web容器調(diào)用,初始化此Filter。
②init(FilterConfig filterConfig)由Web容器調(diào)用,初始化此Filter。
③doFilter(ServletRequest request,ServletResponse response,FilterChain chain)具體過(guò)濾處理代碼。
3.一個(gè)過(guò)濾器框架實(shí)例
SimpleFilter1.java
1
package com.zj.sample;
2
import java.io.IOException;
3
import javax.servlet.Filter;
4
import javax.servlet.FilterChain;
5
import javax.servlet.FilterConfig;
6
import javax.servlet.ServletException;
7
import javax.servlet.ServletRequest;
8
import javax.servlet.ServletResponse;
9
public class SimpleFilter1 implements Filter
{
10
@SuppressWarnings("unused")
11
private FilterConfig filterConfig;
12
public void init(FilterConfig config) throws ServletException
{
13
this.filterConfig = config;
14
}
15
public void doFilter(ServletRequest request, ServletResponse response,
16
FilterChain chain)
{
17
try
{
18
System.out.println("Within SimpleFilter1:Filtering the Request
");
19
chain.doFilter(request, response);// 把處理發(fā)送到下一個(gè)過(guò)濾器
20
System.out .println("Within SimpleFilter1:Filtering the Response
");
21
} catch (IOException ioe)
{
22
ioe.printStackTrace();
23
} catch (ServletException se)
{
24
se.printStackTrace();
25
}
26
}
27
public void destroy()
{
28
this.filterConfig = null;
29
}
30
} SimpleFilter2.java
1
package com.zj.sample;
2
import java.io.IOException;
3
import javax.servlet.Filter;
4
import javax.servlet.FilterChain;
5
import javax.servlet.FilterConfig;
6
import javax.servlet.ServletException;
7
import javax.servlet.ServletRequest;
8
import javax.servlet.ServletResponse;
9
10
public 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ā)送到下一個(gè)過(guò)濾器
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>//為所有的訪問(wèn)做過(guò)濾
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>//為所有的訪問(wèn)做過(guò)濾
17 </filter-mapping>
打開(kāi)web容器中任意頁(yè)面輸出結(jié)果:(注意過(guò)濾器執(zhí)行的請(qǐng)求/響應(yīng)順序)
Within SimpleFilter1:Filtering the Request...
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...
4.報(bào)告過(guò)濾器
我們來(lái)試驗(yàn)一個(gè)簡(jiǎn)單的過(guò)濾器,只要調(diào)用相關(guān)的servlet或JSP頁(yè)面,它就打印一條消息到標(biāo)準(zhǔn)輸出。為實(shí)現(xiàn)此功能,在doFilter方法中執(zhí)行過(guò)濾行為。每當(dāng)調(diào)用與這個(gè)過(guò)濾器相關(guān)的servlet或JSP頁(yè)面時(shí),doFilter方法就生成一個(gè)打印輸出,此輸出列出請(qǐng)求主機(jī)和調(diào)用的URL。因?yàn)?/span>getRequestURL方法位于HttpServletRequest而不是ServletRequest中,所以把ServletRequest對(duì)象構(gòu)造為HttpServletRequest類(lèi)型。我們改動(dòng)一下章節(jié)3的SimpleFilter1.java。
1
package com.zj.sample;
2
import java.io.IOException;
3
import java.util.Date;
4
import javax.servlet.Filter;
5
import javax.servlet.FilterChain;
6
import javax.servlet.FilterConfig;
7
import javax.servlet.ServletException;
8
import javax.servlet.ServletRequest;
9
import javax.servlet.ServletResponse;
10
import javax.servlet.http.HttpServletRequest;
11
12
public 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。
測(cè)試:
輸入[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.訪問(wèn)時(shí)的過(guò)濾器(在過(guò)濾器中使用servlet初始化參數(shù))
下面利用init設(shè)定一個(gè)正常訪問(wèn)時(shí)間范圍,對(duì)那些不在此時(shí)間段的訪問(wèn)作出記錄。我們改動(dòng)一下章節(jié)3的SimpleFilter2.java。
1
package com.zj.sample;
2
import java.io.IOException;
3
import java.text.DateFormat;
4
import java.util.Calendar;
5
import java.util.GregorianCalendar;
6
import javax.servlet.Filter;
7
import javax.servlet.FilterChain;
8
import javax.servlet.FilterConfig;
9
import javax.servlet.ServletContext;
10
import javax.servlet.ServletException;
11
import javax.servlet.ServletRequest;
12
import javax.servlet.ServletResponse;
13
import javax.servlet.http.HttpServletRequest;
14
15
public 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日志處理,這里補(bǔ)充介紹一下。config.getServletContext().log("log message")會(huì)將日志信息寫(xiě)入<CATALINA_HOME>/logs文件夾下,文件名應(yīng)該為localhost_log.2007-03-04.txt這樣的形式(按日期每天產(chǎn)生一個(gè),第二天可以看見(jiàn))。要得到這樣一個(gè)日志文件,應(yīng)該在server.xml中有:
<Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/> |
參考資料
[1] Marty Halls ,Servlet與JSP權(quán)威指南,機(jī)械工業(yè)出版社
[2] 趙強(qiáng),精通JSP編程,電子工業(yè)出版社
本文出自 “子 孑” 博客,請(qǐng)務(wù)必保留此出處http://zhangjunhd.blog.51cto.com/113473/20629