歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java Filter的執行順序

Java Filter的執行順序

日期:2017/3/1 9:58:02   编辑:Linux編程

IMPORTANT: The Container’s rules for ordering filters:1) ALL filters with matching URL patterns are located first. This is NOT the same as the URL mapping rules the Container uses to choose the “winner” when a client makes a request for a resource, because ALL filters that match will be placed in the chain!! Filters with matching URL patterns are placed in the chain in the order in which they are declared in the DD.BeerRequest1*.doBeerRequest2AdviceServletWrite down the sequence in which the filters will be executed for each request path. Assume Filter1 - Filter5 have been properly declared.

When more than one filter is mapped to a given resource, the Container uses the following rules:

2) Once all filters with matching URLs are placed in the chain, the Container does the same thing with filters that have a matching in the DD.

說白了就兩條:

1)先執行帶有url-pattern標簽的filter,再執行帶有servlet-name標簽的filter。兩種標簽的書寫方式如下:

<filter-mapping>
<filter-name>BeerRequest1</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping><filter-mapping>
<filter-name>BeerRequest2</filter-name>
<servlet-name>AdviceServlet</servlet-name>
</filter-mapping>

前者優先執行。

2)如果同為url-pattern或servlet-name,則會按照在web.xml中的聲明順序執行。

下面舉個例子:

<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/Recipes/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter2</filter-name>
<servlet-name>/Recipes/HopsList.do</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Filter3</filter-name>
<url-pattern>/Recipes/Add/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter4</filter-name>
<servlet-name>/Recipes/Modify/ModRecipes.do</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Filter5</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Request path Filter Sequence
/Recipes/HopsReport.do 1, 5
/Recipes/HopsList.do 1, 5, 2
/Recipes/Modify/ModRecipes.do 1, 5, 4
/HopsList.do 5
/Recipes/Add/AddRecipes.do 1, 3, 5

Copyright © Linux教程網 All Rights Reserved