This is a example on filter order execution in Servlets and JSP in Hed first Book
He tells us to write the order in which the filters will be executed. It is gives as bellow
The url pattern given is
/Recipes/HopsReport.do (according to me 1,5) (what actually is 1,5)
/Recipes/HopsList.do (according to me 1,2,5) (what actually is 1,5,2)
/Recipes/Modify/ModRecipes.do (according to me 1,4,5) (what actually is 1,5,4)
/HopsList.do (according to me 5) (what actually is 5)
/Recipes/Add/AddRecipes.do (according to me 1,3,5) (what actually is 1,3,5)
The order should be the order in which they have been declared. According to that for second one it should be 1,2,5 but in the book it is mentioned as 1,5,2. I don't get it. Filter5 is declared after Filter2. But still Filter5 get executed before Filter2. So is the case with all other urls. Where my understanding is wrong. please help me.
While building the filter chain servlet uses <url-pattern> matches first and then <servlet-name> matches later in the order they specified in the DD. That means if filters 1 2 3 matched with <url-pattern> these will be added to filter chain, and then if filter 4 and filter 5 matches with <servlet-name> these will be added later. So now filter chain has filters 1 2 3 4 5 in the order.
If <url-pattern> in DD is in the order filters 3 1 2 then the final order is 3 1 2 4 5.
Hope this helps.
Sai Surya, SCJP 5.0, SCWCD 5.0, IBM 833 834
http://sai-surya-talk.blogspot.com, I believe in Murphy's law.
Joined: Jan 13, 2008
Sorry, I didn't get you. Take the example of second url.
it first matches with Filter1 then Filter2 (since it is in that order before Filter5) and then finally Filter5. Thus according to me it should have been 1,2,5
But in the book it is mentioned as 1,5,2 How come it is able to match with Filter5 even though it is the last one to match because of the order in which it has been written.
As I said, the container has to build the filter chain to execute the filters. While building the filter chain the container uses the following rule.
- It adds all the filters matching <url-pattern> to filter chain in the order they're declared in DD.
- It adds all the filters matching <servlet-name> to filter chain in the order they're declared in DD.
In our example, filter 1 and filter 5 are matched based on <url-pattern>, then finally only one match found using <servlet-name> which is filter 2.
So the order of executing is 1 5 2.
Refer HFSJ Second Edition page no. 710. (I've PDF version)