springboot筆記(web篇)

1、webjars 以jar包/maven依賴引入靜態文件

//讀取靜態文件方法
WebMvcAuotConfiguration.addResourceHandlers()
//讀取路徑
customizeResourceHandlerRegistration(registry
						.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod))
						.setCacheControl(cacheControl));

2、其他靜態文件

//讀取靜態文件方法
WebMvcAuotConfiguration.addResourceHandlers()
//讀取路徑
if (!registry.hasMappingForPattern(staticPathPattern)) {
	customizeResourceHandlerRegistration(
		registry.addResourceHandler(staticPathPattern)
				.addResourceLocations(getResourceLocations(
					this.resourceProperties.getStaticLocations()))
				.setCachePeriod(getSeconds(cachePeriod))
				.setCacheControl(cacheControl));
}

 代碼結構圖

 所以靜態資源讀取路徑爲

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/",
			"classpath:/resources/",
			"classpath:/static/",
			"classpath:/public/"
		};

 

3、獲取歡迎頁(WebMvcAutoConfiguration.welcomePageHandlerMapping() )

public class WebMvcAutoConfiguration {

    //.........

	private Optional<Resource> getWelcomePage() {
		String[] locations = getResourceLocations(
				this.resourceProperties.getStaticLocations());//獲取路徑
		return Arrays.stream(locations).map(this::getIndexHtml)//獲取文件名
				.filter(this::isReadable).findFirst();
	}

	private Resource getIndexHtml(String location) {
		return this.resourceLoader.getResource(location + "index.html");
	}
}

//具體路徑
public class ResourceProperties{
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
		"classpath:/META-INF/resources/",
		"classpath:/resources/",
		"classpath:/static/",
		"classpath:/public/" 
	};
}

 

4、圖標映射

Spring Boot 會在靜態資源目錄下 與 根路徑(按該順序) 查找  favicon.ico 文件;
如果存在這樣的文件,Spring Boot 會自動將其設置爲應用圖標

具體路徑:

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/: 當前項目根路徑下  

 

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