Servlet之过滤器Filter

来源:互联网 发布:源码出售001zhan 编辑:程序博客网 时间:2024/06/04 18:36
一、Filter简介

  Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。

  Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截。

二、Filter是如何实现拦截的?
  Filter接口中有一个doFilter方法,当我们编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:
调用目标资源之前,让一段代码执行。
是否调用目标资源(即是否让用户访问web资源)。
调用目标资源之后,让一段代码执行。
  web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对 象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方 法,即web资源就会被访问,否则web资源不会被访问。

三、Filter开发
3.1、Filter开发步骤
  Filter开发分为二个步骤:
编写java类实现Filter接口,并实现其doFilter方法。
在 web.xml 文件中使用<filter>和<filter-mapping>元素对编写的filter类进行注册,并设置它所能拦截的资源。

3.2、Filter链
  在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。
  web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。

四、Filter的生命周期
4.1、Filter的创建
  Filter的创建和销毁由WEB服务器负责。 web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作,filter对象只会创建一次,init方法也只会执行一次。通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
4.2、Filter的销毁
  Web容器调用destroy方法销毁Filter。destroy方法在Filter的生命周期中仅执行一次。在destroy方法中,可以释放过滤器使用的资源。
4.3、FilterConfig接口
  用户在配置filter时,可以使用<init-param>为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得:
  String getFilterName():得到filter的名称。
  String getInitParameter(String name): 返回在部署描述中指定名称的初始化参数的值。如果不存在返回null.
  Enumeration getInitParameterNames():返回过滤器的所有初始化参数的名字的枚举集合。
  public ServletContext getServletContext():返回Servlet上下文对象的引用。


web.xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>filter</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 编码过滤器 --><filter><filter-name>setCharacterEncoding</filter-name><filter-class>dhp.filter.EncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>setCharacterEncoding</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 请求url日志记录过滤器 --><filter><filter-name>logfilter</filter-name><filter-class>dhp.filter.LogFilter</filter-class></filter><filter-mapping><filter-name>logfilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>helloWorld</servlet-name><servlet-class>dhp.hello.HelloWorldServlet</servlet-class></servlet><servlet-mapping><servlet-name>helloWorld</servlet-name><url-pattern>/servlet/HelloWorldServlet</url-pattern></servlet-mapping></web-app>

编码拦截器

package dhp.filter;import java.io.IOException;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;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 EncodingFilter implements Filter {private String encoding;private Map<String, String> params = new HashMap<String, String>();// 项目结束时就已经进行销毁@Overridepublic void destroy() {System.out.println("end do the encoding filter!");params = null;encoding = null;}@Overridepublic void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)throws IOException, ServletException {System.out.println("before encoding " + encoding + " filter!");req.setCharacterEncoding(encoding);resp.setCharacterEncoding(encoding);resp.setContentType("text/html;charset="+encoding);chain.doFilter(req, resp);System.out.println("after encoding " + encoding + " filter!");System.err.println("----------------------------------------");}// 项目启动时就已经进行读取@Overridepublic void init(FilterConfig config) throws ServletException {System.out.println("begin do the encoding filter!");encoding = config.getInitParameter("encoding");for (Enumeration e = config.getInitParameterNames(); e.hasMoreElements();) {String name = (String) e.nextElement();String value = config.getInitParameter(name);params.put(name, value);}}}

日志拦截器

package dhp.filter;import java.io.IOException;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 LogFilter implements Filter {FilterConfig config;  @Override       public void destroy() {          this.config = null;      }  @Override    public void doFilter(ServletRequest req, ServletResponse res,              FilterChain chain) throws IOException, ServletException {          // 获取ServletContext 对象,用于记录日志          ServletContext context = this.config.getServletContext();          //long before = System.currentTimeMillis();          System.out.println("before the log filter!");          //context.log("开始过滤");          // 将请求转换成HttpServletRequest 请求          HttpServletRequest hreq = (HttpServletRequest) req;          // 记录日志          System.out.println("Log Filter已经截获到用户的请求的地址:"+hreq.getServletPath() );          //context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());          try {              // Filter 只是链式处理,请求依然转发到目的地址。              chain.doFilter(req, res);          } catch (Exception e) {              e.printStackTrace();          }          System.out.println("after the log filter!");          //long after = System.currentTimeMillis();          // 记录日志          //context.log("过滤结束");          // 再次记录日志          //context.log(" 请求被定位到" + ((HttpServletRequest) req).getRequestURI()          //      + "所花的时间为: " + (after - before));      }  @Override    public void init(FilterConfig config) throws ServletException {          System.out.println("begin do the log filter!");          this.config = config;      }  }

HelloWorldServlet 类

package dhp.hello;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class HelloWorldServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("doget...");  doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("dopost...");  }@Overrideprotected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {System.out.println("doservice..."+this.getInitParameter("encoding"));super.service(arg0, arg1);}}

访问:http://localhost:8080/filter/servlet/HelloWorldServlet 结果


0 0
原创粉丝点击