业务需求
通过Servlet模拟监听器, 实现部署应用程序加载时并初始化servlet,来获取自定义的上传路径
解决方案
Servlet设启动级别loadOnStartup : 标记容器是否在启动的时候就加载这个servlet。
<load-on-startup>1</load-on-startup>
当值为0或者大于0时,表示容器在应用启动时就加载这个servlet;
当是一个负数时或者没有指定时,则指示访问容器中servle的urlPatterns映射路径时才加载。
loadOnStartup 配置加载 启动顺序 值越小 越优先 必须同时配置属性 value 否则无法直接加载
而在测试需求中
此Servlet需要项目加载时就需要获取的上传路径,而是不需要URL访问 所以不需要配置 servlet-mapping 访问映射 urlPatterns
注解实现
Servlet3.0提供了注解(annotation),使得不再需要在web.xml文件中进行Servlet的部署描述
完成了一个使用注解描述的Servlet程序开发。
使用@WebServlet将一个继承于javax.servlet.http.HttpServlet的类定义为Servlet组件。
@WebServlet有很多的属性:
1、asyncSupported: 声明Servlet是否支持异步操作模式。
2、description: Servlet的描述。
3、displayName: Servlet的显示名称。
4、initParams: Servlet的init参数。
5、name: Servlet的名称。
6、urlPatterns: Servlet的访问URL。
7、value: Servlet的访问URL。
Servlet的访问URL是Servlet的必选属性,可以选择使用urlPatterns或者value定义。
原理分析
Servlet specification:
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 元素标记容器是否应该web应用程序启动时加载(实例化并调用init())
2)它的值必须是一个整数,表示servlet应该被载入的顺序
3)如果该元素不存在或者这个数为负时,则容器会当该Servlet被请求时,再加载。
4)当值为0或者大于0时,表示容器必须在部署应用程序时加载并初始化servlet
5)正数的值越小,该servlet的优先级越高,应用启动时就越先加载。
6)当值相同时,容器就会自己选择顺序来加载。
代码测试
@WebServlet( name="InitServlet",loadOnStartup = 1, value="",
initParams = { @WebInitParam(name="uplaodPath", value="../103_5_images_goods")})
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String path = "../images";
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet初始化上传路径配置");
String temp = config.getInitParameter("uplaodPath");
System.out.println( temp );
}
}
效果展示

注意事项
在注解中必须同时配置属性 value="" 否则Servlet将无法被加载 控制台无输出
参考博客:
Servlet的配置参数load-on-startup参数理解