Web使用部署描述符(Deploy Descriptor)中Filter的执行顺序
Web应用部署描述符(Deploy Descriptor)中Filter的执行顺序
J2EE Web应用的部署描述符DD对于Web开发人员通常都不会陌生,不过某些细节的问题,不好好研究一下Servlet的规范,就可能有些模糊了。
今天遇到个问题:当一个被请求的Web资源符合多个Filter配置的mapping规则时,这些Filter执行的顺序是怎样的?是根据filter标签本身在web.xml中定义的顺序执行,还是根据filter-mapping标签在web.xml中定义的顺序执行呢?
这个问题网上很多人的说法非常模糊,并没有清楚区分两者的顺序区别(其实在绝大部分场景中,两者的顺序通常是一致的)。终于在Sun当年给出的web.xml的XSD文件中,找到问题比较清楚的说明。
<xsd:complexType name="filter-mappingType"> <xsd:annotation> <xsd:documentation> Declaration of the filter mappings in this web application is done by using filter-mappingType. The container uses the filter-mapping declarations to decide which filters to apply to a request, and in what order. The container matches the request URI to a Servlet in the normal way. To determine which filters to apply it matches filter-mapping declarations either on servlet-name, or on url-pattern for each filter-mapping element, depending on which style is used. The order in which filters are invoked is the order in which filter-mapping declarations that match a request URI for a servlet appear in the list of filter-mapping elements.The filter-name value must be the value of the filter-name sub-elements of one of the filter declarations in the deployment descriptor. </xsd:documentation> </xsd:annotation> <xsd:sequence> <xsd:element name="filter-name" type="javaee:filter-nameType"/> <xsd:choice minOccurs="1" maxOccurs="unbounded"> <xsd:element name="url-pattern" type="javaee:url-patternType"/> <xsd:element name="servlet-name" type="javaee:servlet-nameType"/> </xsd:choice> <xsd:element name="dispatcher" type="javaee:dispatcherType" minOccurs="0" maxOccurs="4"/> </xsd:sequence> <xsd:attribute name="id" type="xsd:ID"/> </xsd:complexType>这里主要看上面的documentation部分的描述,可以看到, filter的触发顺序是按照filter-mapping的定义顺序执行的,而并非filter定义在web.xml中的顺序。