Servlet中filter的执行顺序以及urlPatterns和servletNames之间的关系

来源:互联网 发布:mac怎么设置iphone铃声 编辑:程序博客网 时间:2024/05/16 00:42

servlet3.0以前

用web.xml中的<filter-mapping>顺序决定filter的执行顺序

<span style="white-space:pre"></span><filter><filter-name>firstfilter</filter-name><filter-class>filter.FirstFilter</filter-class></filter><filter><filter-name>secondfilter</filter-name><filter-class>filter.SecondFilter</filter-class></filter><filter-mapping><filter-name>firstfilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter-mapping><filter-name>secondfilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

执行结果


servlet3.0以后

通过注解配置filter时,没有专门的指令来配置filter执行的先后。确定filter执行的先后是根据filter类名的字母表顺序


声明filter
@WebFilter(filterName = "second", urlPatterns = { "/*" })public class SecondFilter implements Filter {}@WebFilter(filterName = "first", urlPatterns = { "/*" })public class FirstFilter implements Filter {}
执行结果


@WebFilter(filterName = "second", urlPatterns = { "/*" })public class SecondFilter implements Filter {}@WebFilter(filterName = "first", urlPatterns = { "/*" })public class ZFirstFilter implements Filter {}

执行结果



可以在web.xml中单独写入<filter-mapping>配置filter顺序。

<span style="white-space:pre"></span><filter-mapping><filter-name>firstfilter</filter-name></filter-mapping><filter-mapping><filter-name>secondfilter</filter-name></filter-mapping>

另urlPatterns和servletNames之间的关系

Configuring a Chain of Filters

WebLogic Server creates a chain of filters by creating a list of all the filter mappings that match an incoming HTTP request. The ordering of the list is determined by the following sequence:

  1. Filters where the filter-mapping element contains a url-pattern that matches the request are added to the chain in the order they appear in the web.xml deployment descriptor.
  2. Filters where the filter-mapping element contains a servlet-name that matches the request are added to the chain after the filters that match a URL pattern.
  3. The last item in the chain is always the originally requested resource.

In your filter class, use the FilterChain.doFilter() method to invoke the next item in the chain.


0 0
原创粉丝点击