摘自
http://zhangjunhd.blog.51cto.com/113473/20629/
1.Servlet过滤器
1.1 什么是过滤器
过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择:
①以常规的方式调用资源(即,调用servlet或JSP页面)。
②利用修改过的请求信息调用资源。
③调用资源,但在发送响应到客户机前对其进行修改。
④阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。
1.2 Servlet过滤器的基本原理
在Servlet作为过滤器使用时,它可以对客户的请求进行处理。处理完成后,它会交给下一个过滤器处理,这样,客户的请求在过滤链里逐个处理,直到请求发送到目标为止。例如,某网站里有提交“修改的注册信息”的网页,当用户填写完修改信息并提交后,服务器在进行处理时需要做两项工作:判断客户端的会话是否有效;对提交的数据进行统一编码。这两项工作可以在由两个过滤器组成的过滤链里进行处理。当过滤器处理成功后,把提交的数据发送到最终目标;如果过滤器处理不成功,将把视图派发到指定的错误页面。
2.Servlet过滤器开发步骤
开发Servlet过滤器的步骤如下:
①编写实现Filter接口的Servlet类。
②在web.xml中配置Filter。
开发一个过滤器需要实现Filter接口,Filter接口定义了以下方法:
①destory()由Web容器调用,初始化此Filter。
②init(FilterConfig filterConfig)由Web容器调用,初始化此Filter。
③doFilter(ServletRequest 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);// 把处理发送到下一个过滤器
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); // 把处理发送到下一个过滤器
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容器中任意页面输出结果:(注意过滤器执行的请求/响应顺序)
Within SimpleFilter1:Filtering the Request...
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...
4.报告过滤器
我们来试验一个简单的过滤器,只要调用相关的servlet或JSP页面,它就打印一条消息到标准输出。为实现此功能,在doFilter方法中执行过滤行为。每当调用与这个过滤器相关的servlet或JSP页面时,doFilter方法就生成一个打印输出,此输出列出请求主机和调用的URL。因为getRequestURL方法位于HttpServletRequest而不是ServletRequest中,所以把ServletRequest对象构造为HttpServletRequest类型。我们改动一下章节3的SimpleFilter1.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设置不变,同章节3。
测试:
输入[url]http://localhost:8080/Test4Jsp/login.jsp[/url]
结果:
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初始化参数)
下面利用init设定一个正常访问时间范围,对那些不在此时间段的访问作出记录。我们改动一下章节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设置不变。
关于Tomcat日志处理,这里补充介绍一下。config.getServletContext().log("log message")会将日志信息写入<CATALINA_HOME>/logs文件夹下,文件名应该为localhost_log.2007-03-04.txt这样的形式(按日期每天产生一个,第二天可以看见)。要得到这样一个日志文件,应该在server.xml中有:
<Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/> |
参考资料
[1] Marty Halls ,Servlet与JSP权威指南,机械工业出版社
[2] 赵强,精通JSP编程,电子工业出版社
本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/20629