在web.xml文件中指定啟動時(shí)加載
如果load-on-startup元素值為正,則會在Web應(yīng)用程序部署或服務(wù)器啟動時(shí)加載servlet。 它也被稱為servlet的預(yù)初始化。
可以指定傳遞servlet的值(load-on-startup元素指定的值)為正或?yàn)樨?fù)。
load-on-startup元素的優(yōu)點(diǎn)
servlet在第一個請求時(shí)被加載。這意味著它會在第一次請求時(shí)消耗更多的時(shí)間。 如果在web.xml中指定啟動加載,則servlet將在項(xiàng)目部署時(shí)間或服務(wù)器啟動時(shí)加載。 所以,響應(yīng)第一個請求需要較少的時(shí)間。
下面來看一個簡單的web.xml配置load-on-startup元素的示例代碼 -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>helloworld</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>com.yiibai.MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>com.yiibai.BServlet</servlet-name>
<servlet-class>BServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
定義了2個servlet,這兩個servlet將在項(xiàng)目部署或服務(wù)器啟動時(shí)加載。但是,首先將MyServlet加載,然后再加載BServlet。
傳遞負(fù)值
如果傳遞load-on-startup元素為負(fù)值,則此servlet將請求時(shí)第一個加載。