天天看點

Tomcat部署Spring項目

雖然Spring Boot火了一段時間,Spring在舊的項目中還是有不少的用武之地,在Tomcat中部署Spring也是比較基礎的技能。

web.xml

web.xml是tomcat servlet容器部署的描述檔案,在每個需要使用tomcta部署的應用中都需要有這個檔案。

常見标簽:

<context-param>

<servlet>

<filter>

<listner>

參考:

http://wiki.metawerx.net/wiki/Web.xml

ContextLoaderListener

在舊的項目中,我們常看到ContextLoaderListener的這種用法:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
           

它有兩種用途:

  1. 綁定ApplicationContext的生命周期到ServletContext
  2. 自動的建立ApplicationContext,是以你不需要精确的指定去建立ApplicatiionContext,這是一種更友善的用法。
https://stackoverflow.com/questions/11815339/role-purpose-of-contextloaderlistener-in-spring

實際上,我們還有幾種其它的用法,并非要明确的指定ContextLoaderListener

另外用法1:

  1. 先在xml檔案中指定一個Servlet,指定其name,然後在web.xml同目錄下建立一個其名稱字尾加上-servlet的檔案。

如:

<servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
           

然後建立dispatcherServlet-servlet.xml,其與web.xml在同一目錄

另外用法2:

<servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:applicationContext.xml,classpath*:applicationContext-web.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
           

一個錯誤

還有今天一直碰到的一個錯誤,沒來得及解決

Tomcat部署Spring項目

image.png

Spring的項目中依賴了etcd,bean的配置檔案裡一些bean的配置比如redis的連接配接時動态配置的,而動态配置的屬性要在生效之前從etcd中拉取配置。

老的項目代碼寫的有點亂,啟動的時候沒有加載etcd的配置,etcd相關的代碼沒有執行,弄了半天沒弄好。

碰其它的代碼有時候難免有些問題...

最後

今天碰了下一個比較老的項目,關于Tomcat的一些内容有些忘記了,簡單記錄一下。