Introduction of Servlet Filter(了解Servlet之Filter)

时间:2019-06-02 12:53:15   收藏:0   阅读:110

API文档中介绍了public Interface Filter(公共接口过滤器)

Servlet API文档中是这样介绍的:

‘A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. 

Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

Filters are configured in the deployment descriptor of a web application’

已为此设计确定的示例包括:

  1)认证过滤器

  2)记录和审核过滤器

  3)图像转换过滤器

  4)数据压缩过滤器

  5)加密过滤器

  6)标记过滤器

  7)触发资源访问事件的过滤器

  8)XSL / T过滤器

  9)Mime型链式过滤器

 

看了之后还是不太懂是干啥的,想想平时生活中的例子,比如玩游戏的时候队友太坑心态炸了就会发言骂一些脏的词句而显示的是用*代替,这就是过滤器的作用之一。

 

再贴切一点的了解一下过滤器吧:

1.概念

   过滤作用,对从客户端向服务器端发送的请求进行过滤,也可以对服务器端返回的响应进行处理。它使用户可以改变一个request和修改一个 response.。Filter 不是一个servlet,它不能产生一个response,但是它能够在一个request到达servlet之前预处理request,也可以在 response离开servlet时处理response。换句话说,filter其实是客户端与servlet中间的一个传递者,并且它可以对要传递 的东西进行修改。 

 技术分享图片

  注意:过滤器是用来拦截请求和响应的,不能产生响应,而servlet是用来处理请求并产生响应的。

 

2.适用场合

  实现URL级别的权限访问控制,过滤敏感词汇,压缩响应信息等。

 

3.过滤器如何实现拦截

  当客户端发生请求后,在HttpServletRequest 到达Servlet 之前,过滤器拦截客户的HttpServletRequest 。

  根据需要检查HttpServletRequest ,也可以修改HttpServletRequest 头和数据。

  在过滤器中调用doFilter方法,对请求放行。请求到达Servlet后,对请求进行处理并产生HttpServletResponse发送给客户端。

  在HttpServletResponse 到达客户端之前,过滤器拦截HttpServletResponse 。

  根据需要检查HttpServletResponse ,可以修改HttpServletResponse 头和数据。

  最后,HttpServletResponse到达客户端。 

 

4.Filter接口

  Servlet API提供了一个Filter接口,编写的过滤器必须实现该接口。

  http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/Filter.html

 

5.Filter的生命周期

  (1)Filter接口中有三个重要的方法。

  (2)Filter的生命周期

   Filter的创建和销毁由web服务器控制。

 

6.Filter对象——FilterConfig

  用 户在配置filter时,可以使用<init-param>为filter配置一些初始化参数,当web容器实例化Filter对象,调用其 init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过 filterConfig对象的方法,就可获得:

 

7.过滤器链——FilterChain

   FilterChain是servlet容器向开发人员提供的对象,它提供对资源的筛选请求的调用链的视图。过滤器使用FilterChain调用链中的下一个过滤器,或者如果调用过滤器是链中的最后一个过滤器,则调用链末尾的资源。

  一组过滤器对某些web资源进行拦截,那么这组过滤器就称为过滤器链。过滤器的执行顺序和<filter-mapping>有关(谁在前先执行谁)。

技术分享图片

 

 

部分来自:https://www.cnblogs.com/zlbx/p/4888312.html

原文:https://www.cnblogs.com/ren9ie/p/10962526.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!