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.
load-on-startup 元素在web应用启动的时候指定了servlet被加载的顺序,它的值必须是一个整数。如果它的值是一个负整数或是这个元素不存在,那么容器会在该servlet被调用的时候,加载这个servlet。如果值是正整数或零,容器在配置的时候就加载并初始化这个serlvet,容器必须保证值小的优先加载。如果数值相等,容器可以自动选择先加载。
package com.sample.base;
import java.io.File;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
public class Boot extends HttpServlet {
private static final long serialVersionUID = 4177925985208589275L;
private static final Logger logger = Logger.getLogger(Boot.class);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Server booting...");
logger.info("OS Name:" + System.getProperty("os.name"));
logger.info("OS Version:" + System.getProperty("os.version"));
logger.info("OS Architecture:" + System.getProperty("os.arch"));
logger.info("CPU Maybe:" + System.getProperty("sun.cpu.isalist"));
logger.info("JRE Version:" + System.getProperty("java.version"));
logger.info("JRE Runtime:" + System.getProperty("java.runtime.version"));
java.net.URL url = getClass().getClassLoader().getResource("/");
String SERVER_PATH = new File(url.getPath()).getParent() + File.separator;
logger.info("SERVER_PATH:" + SERVER_PATH);
try {
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
super.destroy();
}
}
本文详细介绍了Servlet的load-on-startup元素及其工作原理。当值为正整数或零时,容器将在部署期间加载并初始化Servlet;若为负整数,则在首次请求时加载。文章还提供了一个示例Servlet类,展示了如何实现Servlet的初始化。

被折叠的 条评论
为什么被折叠?



