servlet與filter的加載順序詳解


          項目:3個filter,3個servlet,匹配的url路徑/hello。

 

情況1:servlet沒加<load-on-startup></load-on-startup>情況(web.xml配置順序:first filter,second filter,third filter,first servlet,second servlet,third servlet):

[html]  view plain  copy
 
  1. 初始化tomcat時:  
  2.     this is the first filter init().....  
  3.     this is the third filter init()....  
  4.     this is the second filter init()....  
  5. 請求/hello時:  
  6.     this is the third servlet init()....  
  7.     this is the first filter doFilter()....  
  8.     this is the second filter doFilter()....  
  9.     this is the third filter doFilter()....  
  10.     this is the third servlet doPost()....  

 

結論:初始化只執行filter的init()方法,不執行servlet的init()的方法。請求/hello時,執行最后一個servlet的init()方法,再按順序執行filter。最后執行最后一個servlet的方法。
filter執行循序看<filter-mapping>的。servlet執行順序看<servlet-mapping>的。

 

情況2:servlet加了<load-on-startup></load-on-startup>的情況(配置順序同1)

[html]  view plain  copy
 
  1. 初始化容器時:  
  2.     this is the first filter init().....  
  3.     this is the third filter init()....  
  4.     this is the second filter init()....  
  5.     this is the first servlet init()....  
  6.     this is the second servlet init()....  
  7.     this is the third servlet init()....  
  8. 請求/hello時:  
  9.            this is the first filter doFilter()....  
  10.     this is the second filter doFilter()....  
  11.     this is the third filter doFilter()....  
  12.     this is the third servlet doPost()....  

 

結論:容器初始化時,先初始化所有filter的init()方法。再初始化所有servlet的init()方法。且servlet的init()方法根據load-on-startup值決定執行順序,值越小,越先執行。在請求/hello時,不再執行init()方法。執行循序同1.

=======================================================================================================

總結:


1).filter的init方法在容器初始化時加載。第一次加載容器執行順序隨機,以后再次加載順序以第一次加載順序為准。
2).filter的doFilter方法在請求url時執行,如果有多個filter匹配,則按照<filter-mapping>順序執行(前提是doFilter方法里面最后要調用FilterChain的doFilter方法,這個方法作用是繼續執行下個filter,如果沒有加,則不執行下面的filter)

 

3).serlvet的init方法
a.如果web.xml中配置了<load-on-startup>屬性,則在Tomcat初始化時按其值從小到大的順序加載所有servlet的init方法。
b.如果沒有配置<load-on-startup>屬性,容器初始化時不加載。在請求匹配的url時進行加載,並且只加載最后一個servlet的init方法。其他的servlet不加載。
4).servlet的doGet、doPost方法:在請求匹配的url路徑時加載,而且只加載最后一個servlet的方法,其他方法不加載。 

5).filter和servlet同時存在,且容器初始化都要加載,則先加載filter再加載servlet的init方法。

6).如果請求的url既匹配filter又匹配servlet,並且servlet的init方法沒有在容器初始化加載,則先加載匹配的servlet的最后一個servlet的init方法,再按順序執行filter方法,最后再執行匹配的最后一個servlet方法。

 

注:

在servlet的配置當中,<load-on-startup>5</load-on-startup>的含義是:

標記容器是否在啟動的時候就加載這個servlet。

當值為0或者大於0時,表示容器在應用啟動時就加載這個servlet;

當是一個負數時或者沒有指定時,則指示容器在該servlet被選擇時才加載。

正數的值越小,啟動該servlet的優先級越高。

 

1)load-on-startup元素標記容器是否在啟動的時候就加載這個servlet(實例化並調用其init()方法)。

2)它的值必須是一個整數,表示servlet應該被載入的順序

2)當值為0或者大於0時,表示容器在應用啟動時就加載並初始化這個servlet;

3)當值小於0或者沒有指定時,則表示容器在該servlet被選擇時才會去加載。

4)正數的值越小,該servlet的優先級越高,應用啟動時就越先加載。

5)當值相同時,容器就會自己選擇順序來加載。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM