您的位置:首页 > 其它

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

2015-04-14 17:19 381 查看

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:

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.

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.

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐