1.SpringBoot对静态资源的映射规则
如果我们需用给web项目中添加css/js/html文件的话,我们会发现此时没有webapp目录。
由于springboot是以jar包的方式打包程序的因此是没有webapp目录的。
那么我们的css/js/html文件要保存在什么地方啊???
我们要了解一个Java类“WebMvcAuotConfiguration”,因为与web开发相关的自动配置都是由这个类完成的。
spring-boot-autoconfigure-2.4.0.jar---》META-INF--》spring.factories
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
.setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
}
}
WebProperties.java
private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
{ "classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/" };
1.1静态资源的保存位置所有“/webjars/**”
webjars:将需要使用的静态资源打成jar包,我们如果需要就将整个jar导入值本项目就可以使用了。
静态资源打成jar包查看位置:
以JQuery为例来使用一下webjars方式
1.在pom.xml文件中导入JQuery的jar依赖
<!--导入jquery的jar包-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
导人以后的结果