web.xml

 web.xml加載過程:
   1 啓動WEB項目的時候,容器(如:Tomcat)會讀他的配置文件web.xml讀兩個節點
         <listener></listener>和<context-param></context-param>
    2 緊接着,容器創建一個ServletContext(上下文) 這個WEB項目所有部分都將共享這個上下文
    3 容器將<context-param></context-param>轉化爲鍵值對並交給ServletContext
    4 容器創建<listener></listener>中的類的實例,即創建監聽
    5 在監聽中會有contextInitialized(ServletContextEvent args)初始化方法,在這個方法中獲得:
              ServletContext = ServletContextEvent.getServletContext();   
              context-param的值 = ServletContext.getInitParameter("context-param的鍵"); 

     web.xml節點加載順序
     節點的加載順序與它們在web.xml文件中的先後順序無關。即不會因爲filter寫在listener的前面而會先加載filter最終得出的結論是:listener->filter->servlet
     同時還存在着這樣一種配置節點:context-param,它用於向 ServletContext 提供鍵值對,即應用程序上下文信息。我們的 listener, filter 等在初始化時會用到這些上下文 的信息,那麼context-param 配置節是不是應該寫在 listener 配置節前呢?實際上 context-param 配置節可寫在任意位置,因此真正的加載順序爲:
context-param -> listener -> filter -> servlet
     加載spring
     <listener>  
             <listener-class>  
               org.springframework.web.context.ContextLoaderListener   
            </listener-class>  
       </listener>
     最終結論:

     web.xml 的加載順序是:[context-param -> listener -> filter -> servlet -> spring] ,而同類型節點之間的實際程序調用的時候的順序是根據對應的 mapping 的順序進行調  用的。

    打開web.xml文件,根據實際需要添加如下內容

<!--上下文參數用於log4j以及spring中使用-->
<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<!--應用程序上下文參數,指定spring配置文件位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/beans.xml</param-value>
</context-param> 

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<!--監聽器 用於初始化spring框架-->
<listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章