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/
/: 当前项目根路径下

在哪个文件夹中找到了,就会直接返回

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值