Springmvc web專案初始化
阿新 • • 發佈:2018-11-12
- Web容器首先會讀取專案中的web.xml配置檔案中的兩個節點:<context-param>與<listener>
- Web容器建立ServletContext物件即Servlet上下文,ServletContext代表整個應用,是Servlet的共享區。
- Web容器將<context-param>轉換為鍵值對,並交給ServletContext
- 執行listener(這裡拿ServletContextListen為例),ServletContextListener實現類具有兩個方法:contextInitialized()、contextDestroyed(),用來監聽ServletContext物件的建立與銷燬,當監測到ServletContext物件的建立時,呼叫contextInitialized()方法,將ServletContext物件封裝到方法的事件物件中:在contextInitialized()方法內部程式碼如下:
/*通過事件物件獲取封裝的servletContext物件*/
servletContext=ServletContextEvent.getServletContext();
/*通過鍵值獲得context-param的值*/
Context-param=ServletContext.getInitParameter(“context-param的鍵”)
- 獲得context-param進行相關操作,例如在專案啟動的時候建立資料庫
- 載入filter
- Web容器讀取每個servlet設定資訊(註解或傳統方式配置),並生成代表物件servletconfig,此時將ServletConfig設定在servletconfig中,可以從servletconfig中獲取到servletcontext物件來獲取上下文資訊,例項化servlet在web容器中,收到請求後,servlet開始服務,傳入servletconfig到servlet的init方法中進行servlet初始化(這個過程只進行一次)
綜上,web.xml載入順序為:
context-param->listener->filter->servlet