Spring Boot學習筆記(5)—— 靜態資源映射規則

在springboot項目中,對靜態資源的映射規則, 可通過分析 WebMvcAutoConfiguration(這個類是SpringBoot的底層類,位於:package org.springframework.boot.autoconfigure.web.servlet;) 自動配置類得到

webjars資源映射

WebMvcAuotConfiguration.addResourceHandlers() 分析webjars 資源映射

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
	CacheControl cacheControl = this.resourceProperties.getCache()
			.getCachecontrol().toHttpCacheControl();
	if (!registry.hasMappingForPattern("/webjars/**")) {
	
		//這裏表示:當項目收到 /webjars/** 請求後,會去 classpath:/MATE-INF/resources/webjars/ 下去查找資源文件
		
		customizeResourceHandlerRegistration(registry
				.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/")
				.setCachePeriod(getSeconds(cachePeriod))
				.setCacheControl(cacheControl));
	}
	String staticPathPattern = this.mvcProperties.getStaticPathPattern();
	if (!registry.hasMappingForPattern(staticPathPattern)) {
		customizeResourceHandlerRegistration(
				registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(
								this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod))
						.setCacheControl(cacheControl));
	}
}

所以,所有 /webjars/** 請求,都去 classpath:/META-INF/resources/webjars/ 目錄找對應資源文件,webjars是以jar包的方式來引入靜態資源,例如:

<!--引入 jquery3.3.1 webjars -->
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.3.1</version>
</dependency>

添加上面的依賴之後,就會引入一個 jquery-3.3.1 的jar包,在jar包的
MATE-INF/resources/webjars/jquery/3.3.1/ 下面有一個jquery.js文件,此時可以直接通過訪問項目:localhost:8080/webjars/jquery/3.3.1/jquery.js 來訪問jquery.js文件,因爲是通過webjars方式來映射資源,所以 /webjars/** 請求就相當於 /META-INF/resources/webjars/

其他靜態資源映射

在springboot項目中,當接收到 /** 請求訪問資源時,會被映射到下面的4個類路徑下的靜態資源目錄下查找:
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
查找順序從上往下查找,查找到就返回,查找不到就返回 404,例如,在 classpath:/static/ 文件夾下添加style.css,啓動項目後就可以直接訪問:localhost:8080/style.css

歡迎頁映射

springboot項目,會從 4個靜態資源目錄 + 根路徑 / 中 查找 index.html 頁面作爲歡迎頁(**注意:**一定是index.html)
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/: 當前項目根路徑下

會在 靜態資源目錄下 與 根路徑查找 (按該順序) index.html頁面;
請求映射訪問 localhost:8080/ 會在上面5個目錄中查找 index.html 頁面(因爲/也屬於 /** )

圖標映射

Spring Boot 會在靜態資源目錄下 與 根路徑(按該順序) 查找 favicon.ico (注意:名稱一定要是 favicon.ico
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/: 當前項目根路徑下

在哪個文件夾中找到了,就會直接返回

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章