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

本文详细介绍了在不同版本的Servlet规范中,过滤器(Filter)执行顺序的确定方式。包括3.0之前的版本如何通过web.xml配置文件中的<filter-mapping>元素顺序来决定,以及3.0之后版本中如何通过类名的字母表顺序来确定执行顺序。此外还提到了可以通过混合使用注解和web.xml来调整执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值