web-filter--过滤器

  1. Filter过滤器
    Filter和Servlet及Listener称之为Servlet三大技术。
    Filter是一个过滤器,可以将请求或响应拦截,拦截中的请求或响应,可以对其中的内容进行操作。操作完成后,可以选择放行或不放行当前请求或响应。

    1. Filter的创建
      a. 创建一个类,实现Filter接口,即可成为一个过滤器。
      package cn.tedu.filter;

      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 FilterDemo1 implements Filter {

      public void init(FilterConfig filterConfig) throws ServletException {
      System.out.println(“FilterDemo1…begin…”);

      }

      public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
      //放行请求响应。如果不书写,则代表不放行。

      //放行代码的前后,可以添加额外操作
      System.out.println(“doFilter…before…”);
      chain.doFilter(request, response);
      System.out.println(“doFilter…end…”);

      }

public void destroy() {
System.out.println(“FilterDemo1…end…”);

		        }
		
		}

b. 在web.xml文件中添加filter标签及filter-mapping


FilterDemo1
cn.tedu.filter.FilterDemo1



FilterDemo1
/*

注意:filter在web.xml中的配置和servlet十分相似,只是filter-mapping中的url-pattern表示拦截的映射路径,符合url-pattern中的路径的url都会被过滤器拦截。
c. Filter方法实现
Method Summary
void destroy()
Called by the web container to indicate to a filter that it is being taken out of service.
在filter被移除web容器时,会自动调用destroy方法,完成善后的操作。
移除web容器:删除web应用 。关闭tomcat
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
在过滤器拦截到请求之后,请求对应的响应,也会被过滤器拦截,请求响应只要被拦截都会经过这个dofilter方法。在这个方法中可以对请求响应中的数据,作出处理。处理完成之后,可以选择放行或不放行。 chain.doFilter(request,response);
如果放行,在放行代码的前后,还可以添加额外的操作。
void init(FilterConfig filterConfig)
Called by the web container to indicate to a filter that it is being placed into service.
在web容器启动时,filter被自动加载到web容器中,会自动调用init方法完成初始化的操作。

  1. 责任链模式
    在过滤器中存在责任链模式。所谓责任链就是多个过滤器组成的链。如果有任何一个过滤器没有放行,则这个请求无法到达对应的web资源。

    a. 当配置多个Filter过滤器时,它们存在一定的拦截顺序,这个拦截顺序由filter-mapping的配置顺序来决定。

    1. 过滤器的生命周期
      当服务器启动,filter会随着服务器的启动而加载,自动调用init方法完成初始化的操作,提供拦截请求与响应的服务。在拦截到请求或响应后,会通过doFilter方法。在doFilter方法中,可以选择放行或不放行请求响应。如果放行,则在放行前后可以添加额外的操作。如果不放行,不能调用chain.doFilter(request,response);在服务器关闭的时候,filter会随着服务器的关闭而销毁。在销毁之前会自动调用destroy方法完成善后操作。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值