2011年5月15日 星期日

web.xml中的load-on-startup標籤

在寫WEB應用程式時
web.xml這個檔很重要
他記載了該應用程式所需要被使用到的資源

例如: Servelet, Filterk 和 Listener等
你光有程式還不行
必須還要再web.xml中加以登記
Web Container, 例如Apache Tomcat, IBM WebSphere, 在啟動時
才會找到該類別

這裡我只有講"找到", 但是並沒有講"載入"
是因為載入的時機有兩個
一個是Web Container啟動時
另一個就是該Servlet第一次被使用時
Web Container會自己選擇該怎樣載入
但無論如何
該Servlet的instance一定會在被使用前就準備好
(準備好後並不是會一直在那
例如空間不夠用時
Web Container可能會把一些已建立好的instance砍掉
但Web Container保證一定會在下一次該Servlet被使用前
先把它的instance準備好
)

於是如果今天想要強迫Web Container啟動時
1.就要載入特定的Servlet
2.並且指定載入的順序
那麼就需要<load-on-startup>標籤了

他的使用方式
是夾在<servlet>之間
例如:

<servlet>

<servlet-name>abc<servlet-name>

<servlet-class>my.abc</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>
 
至於<load-on-startup>的內容, 是一個整數. 可以正, 可以負, 也可以是0,
在網路上人家說J2EE Specilization 裡面有這一段
介紹這個標籤的用法
:(但是我找不到原文出處)
 
The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.


上面這段內容說
1.如果<load-on-startup>的內容是0或正的整數, Web Container會依由小到大的順序, 來載入並初始話該Servlet. 於是載入順序就是: 0->1->2->3
2.如果<load-on-startup>的內容是負的整數, 或是沒有內容. 那Web Container就會自行選擇載入時機.

但是如果有兩個Servlet都是標示為2,
那順序是誰先誰後呢?

經過我的測試
是每次都不一樣.
因為我有兩個Servlet, 姑且稱為A和B
A是proxool連接池, 用來載入連接池設定檔的Servlet
然後B會利用 DriverManager.getConnection("proxool.example")來獲取資料庫連線
想當然爾
A必須要先載入->初始
然後B才能利用proxool.example這樣的別名
去取得連線,
否則會出現找不到對應的Driver訊息.

我試了幾次
有幾次B連線成功
有幾次連線失敗

後來把B的<load-on-startup>改為3
則無論試了N次都能連線成功

所以結論就是:
如果兩個Servlet的載入有相依關係
務必讓它們的<load-on-startup>值改為一前一後

1 則留言: