servlet與filter的加載順序詳解 -开发者知识库
情況1:servlet沒加<load-on-startup></load-on-startup>情況(web.xml配置順序:first filter,second filter,third filter,first servlet,second servlet,third servlet):
- 初始化tomcat時:
- this is the first filter init().....
- this is the third filter init()....
- this is the second filter init()....
- 請求/hello時:
- this is the third servlet init()....
- this is the first filter doFilter()....
- this is the second filter doFilter()....
- this is the third filter doFilter()....
- 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)
- 初始化容器時:
- this is the first filter init().....
- this is the third filter init()....
- this is the second filter init()....
- this is the first servlet init()....
- this is the second servlet init()....
- this is the third servlet init()....
- 請求/hello時:
- this is the first filter doFilter()....
- this is the second filter doFilter()....
- this is the third filter doFilter()....
- 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方法。最佳答案: