SpringBoot静态资源映射规则。
首先找到Spring Boot静态资源配置类(如下图所示):ResourceProperties.java
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
/**
* Whether to enable default resource handling.
*/
private boolean addMappings = true;
private final Chain chain = new Chain();
private final Cache cache = new Cache();
public String[] getStaticLocations() {
return this.staticLocations;
}
了解了SpringBoot的自动配置原理:
- xxxxAutoConfiguration:自动配置类,给容器中自动添加组件。
- xxxxProperties:配置文件封装类,封装配置文件中的内容。
找到WebMvcAutoConfiguration
类:
(1)所有的/webjars/**,都会去classpath:/META-INF/resources/webjars/找资源;webjars是以jar包的方式引入静态资源。
示例演示:
在pom.xml文件中添加依赖:
<!--引入jquery-webjars-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
在浏览器中进行测试:访问:http://127.0.0.1:8080/webjars/jquery/3.5.1/jquery.js
(2)“/**”访问当前项目的任何资源,SpringBoot自动会到以下的目录中访问静态资源。
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- / ——项目的根路径
注意:静态资源文件的加载顺序:META/resources->resources->static->public
欢迎页的映射:
(3)欢迎页:静态资源文件夹下面的index.html页面;被/**所映射。
示例:
在项目的resources目录下创建public文件夹,在该public文件下面创建一个简单的index.html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<b>这是首页</b>
</body>
</html>
还可以在application.properties配置文件中进行自定义静态资源文件夹:
#自定义静态资源文件夹hello
#spring.resources.static-locations=classpath:/hello