加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

深入解析Java的Servlet过滤器的原理及其应用

发布时间:2020-05-23 05:03:03 所属栏目:Java 来源:互联网
导读:1.Servlet过滤器1.1什么是过滤器过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作

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,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,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,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,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));
    }
  }
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读