1、源码分析
WebMvcAutoConfiguration
@Configuration
...
public class WebMvcAutoConfiguration {
@Configuration
...
// 静态内部类
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
// 添加资源处理
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 判断是否有自定义资源路径
if (!this.resourceProperties.isAddMappings()) {
// 如果有自定义资源路径,则默认资源失效
logger.debug("Default resource handling disabled");
} else {
// 没有自定义资源路径,就在默认路径下查找
// 方式一:webjars
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
// 方式二:四个固定路径
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
}
}
- this.resourceProperties.getStaticLocations()
@ConfigurationProperties
...
public class WebProperties {
...
// 静态内部类
public static class Resources {
// 四个默认路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
...
public String[] getStaticLocations() {
return this.staticLocations;
}
}
}
2、方式一:webjars
Webjars本质就是以jar包的方式引入静态资源
官网:https://www.webjars.org
使用jQuery
- 导jar包
<!--导入jar包-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
- 页面使用
-
省略版本号
导入额外webjars-locator依赖jar包
<dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> <version>0.42</version> </dependency>
3、方式二:4个固定路径
项目中要是使用自己的静态资源,可以在resources根目录下新建对应的文件夹,就可以存放自已的静态文件
// 四个默认路径:优先级从前向后,由高到低
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"
};
优先级:1 > 2 > 3 > 4
4、方式三:自定义路径
也可以在配置文件中指定静态资源文件(不推荐)
一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!
- application.yml
spring:
web:
resources:
static-locations:
- classpath:/js/
- classpath:/css/