日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Servlet配置啟動級別loadOnStartup注意事項

作者:夢凝哲雪 更新時間: 2022-02-25 編程語言

業務需求

通過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)當值相同時,容器就會自己選擇順序來加載。

代碼測試

/**
 * 此Servlet不需要URL訪問   所以不需要配置 servlet-mapping 訪問映射  urlPatterns
 * loadOnStartup 配置加載   啟動順序  值越小 越優先 必須同時配置屬性 value 否則無法激活
 * company 源辰信息
 * @author 38929
 * @date 2021年7月28日
 * @version 1.0
 * Email 1198865589@qq.com
 */
@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參數理解

原文鏈接:https://blog.csdn.net/Klhz555/article/details/119321434

欄目分類
最近更新