servlet與filter的載入順序詳解

2021-07-05 05:41:35 字數 1914 閱讀 7485

情況1:servlet沒加情況(web.xml配置順序:first filter,second filter,third filter,first servlet,second servlet,third servlet):

[html]view plain

copy

初始化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()....  

情況2:servlet加了的情況(配置順序同1)

[html]view plain

copy

初始化容器時:  

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.

總結:

dofilter方法,這個方法作用是繼續執行下個filter,如果沒有加,則不執行下面的filter)

3).serlvet的init方法

a.如果web.xml中配置了屬性,則在tomcat初始化時按其值從小到大的順序載入所有servlet的init方法。

b.如果沒有配置屬性,容器初始化時不載入。在請求匹配的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方法。

Java中Filter與Servlet的區別和聯絡

filter servlet介面 實現filter介面 實現servlet介面 使用步驟 1 建立類,繼承介面 2 實現方法 init dofilter destroy 3 配置web inf web.xml 1 建立類,繼承介面 2 實現方法 init service destroy getser...

Filter與Servlet的區別和聯絡

filter servlet介面 實現filter介面 實現servlet介面 使用步驟 1 建立類,繼承介面 2 實現方法 init dofilter destroy 3 配置web inf web.xml 1 建立類,繼承介面 2 實現方法 init service destroy getser...

Filter與Servlet的區別和聯絡

filter servlet介面 實現filter介面 實現servlet介面 使用步驟 1 建立類,繼承介面 2 實現方法 init dofilter destroy 3 配置web inf web.xml 1 建立類,繼承介面 2 實現方法 init service destroy getser...