問題:#
- filterChain 是什麼時候執行的呢?
- filterChain 中的 filter 來源何處?
- standardContext 什麼時候開始收集的過濾器集合
1. filterChain 是什麼時候執行的呢?#
在 org.apache.catalina.core.StandardWrapperValve 類中有如下一個方法
我們一會兒回過頭來看它是如何創建過濾器鏈對象的代碼,我們先來看它是如何執行過濾器鏈的,過濾器鏈對象執行的流程實現:
從 filterChain 類的源碼可以看出底層是包含了所匹配上的 filter 陣列,也就是添加進去匹配上過濾器對象是有序的,添加的時候就決定了。
那麼它是什麼時候添加的呢?
2. filterChain 中的 filter 來源何處?#
其實在 org.apache.catalina.core.StandardWrapperValve 類的 invoke 方法中
可以看出在創建 filterChain 對象時,從 ServletContext 獲取所有註冊的 filter 的陣列取出需要的添加到這次請求創建的 filterChain 對象,而且 servletContext 對象的註冊的所有的過濾器本身就是一個陣列(本身就是有序的),所以遍歷匹配的時候,也就是有序的。
3. ServletContext 什麼時候開始收集的陣列#
filterMaps 在 StandardContext 類中
啟動 tomcat,我們可以根據堆棧查看調用順序
StandardContext.startInternal()-->fireLifecycleEvent()-->ContextConfig.lifecycleEvent()-->ContextConfig.lifecycleEventcon-->ContextConfig.con.figureStart()-->ContextConfig.webConfig()
查看方法
這裡就將 web.xml 收集到所有 filter 的 set 集合,然後將收集到的 filter 集合轉換成陣列,設置給 StandardContext 對象