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
package com.zj.sample;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse; public class SimpleFilter1 implements Filter { @SuppressWarnings("unused") private FilterConfig filterConfig; public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try { System.out.println("Within SimpleFilter1:Filtering the Request..."); chain.doFilter(request, response);// 把处理发送到下一个过滤器 System.out .println("Within SimpleFilter1:Filtering the Response..."); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ServletException se) { se.printStackTrace(); } } public void destroy() { this.filterConfig = null; }}
SimpleFilter2.java
package com.zj.sample;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse; public class SimpleFilter2 implements Filter { @SuppressWarnings("unused") private FilterConfig filterConfig; public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try { System.out.println("Within SimpleFilter2:Filtering the Request..."); chain.doFilter(request, response); // 把处理发送到下一个过滤器 System.out.println("Within SimpleFilter2:Filtering the Response..."); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ServletException se) { se.printStackTrace(); } } public void destroy() { this.filterConfig = null; }}
web.xml
<filter> <filter-name>filter1</filter-name> <filter-class>com.zj.sample.SimpleFilter1</filter-class></filter><filter-mapping> <filter-name>filter1</filter-name> <url-pattern>/*</url-pattern>//为所有的访问做过滤</filter-mapping> <filter> <filter-name>filter2</filter-name> <filter-class>com.zj.sample.SimpleFilter2</filter-class></filter><filter-mapping> <filter-name>filter2</filter-name> <url-pattern>/*</url-pattern>//为所有的访问做过滤</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。
SimpleFilter1.java
package com.zj.sample;import java.io.IOException;import java.util.Date;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest; public class SimpleFilter1 implements Filter { @SuppressWarnings("unused") private FilterConfig filterConfig; public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try { System.out.println("Within SimpleFilter1:Filtering the Request..."); HttpServletRequest req = (HttpServletRequest) request; System.out.println(req.getRemoteHost() + " tried to access " + req.getRequestURL() + " on " + new Date() + "."); chain.doFilter(request, response); System.out.println("Within SimpleFilter1:Filtering the Response..."); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ServletException se) { se.printStackTrace(); } } public void destroy() { this.filterConfig = null; }}
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。
SimpleFilter2.java。
package com.zj.sample;import java.io.IOException;import java.text.DateFormat;import java.util.Calendar;import java.util.GregorianCalendar;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest; public class SimpleFilter2 implements Filter { @SuppressWarnings("unused") private FilterConfig config; private ServletContext context; private int startTime, endTime; private DateFormat formatter; public void init(FilterConfig config) throws ServletException { this.config = config; context = config.getServletContext(); formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); try { startTime = Integer.parseInt(config.getInitParameter("startTime"));// web.xml endTime = Integer.parseInt(config.getInitParameter("endTime"));// web.xml } catch (NumberFormatException nfe) { // Malformed or null // Default: access at or after 10 p.m. but before 6 a.m. is // considered unusual. startTime = 22; // 10:00 p.m. endTime = 6; // 6:00 a.m. } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try { System.out.println("Within SimpleFilter2:Filtering the Request..."); HttpServletRequest req = (HttpServletRequest) request; GregorianCalendar calendar = new GregorianCalendar(); int currentTime = calendar.get(Calendar.HOUR_OF_DAY); if (isUnusualTime(currentTime, startTime, endTime)) { context.log("WARNING: " + req.getRemoteHost() + " accessed " + req.getRequestURL() + " on " + formatter.format(calendar.getTime())); // The log file is under <CATALINA_HOME>/logs.One log per day. } chain.doFilter(request, response); System.out .println("Within SimpleFilter2:Filtering the Response..."); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ServletException se) { se.printStackTrace(); } } public void destroy() {} // Is the current time between the start and end // times that are marked as abnormal access times? private boolean isUnusualTime(int currentTime, int startTime, int endTime) { // If the start time is less than the end time (i.e., // they are two times on the same day), then the // current time is considered unusual if it is // between the start and end times. if (startTime < endTime) { return ((currentTime >= startTime) && (currentTime < endTime)); } // If the start time is greater than or equal to the // end time (i.e., the start time is on one day and // the end time is on the next day), then the current // time is considered unusual if it is NOT between // the end and start times. else { return (!isUnusualTime(currentTime, endTime, startTime)); } }}
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"/>
6.禁止站点过滤器
如果你希望在你的过滤器检测到不正常的异常而中途中断后面的过滤过程时,可这样做:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if (isUnusualCondition(req)) { res.sendRedirect("http://.zj.sample.LongServlet</servlet-class></servlet><servlet-mapping> <servlet-name>LongServlet</servlet-name> <url-pattern>/LongServlet</url-pattern></servlet-mapping>