1. 静态资源映射规则在项目中双击shift或ctrl+n搜索webmvcautoconfiguration.class文件,文件中的addresourcehandlers方法如下:
public void addresourcehandlers(resourcehandlerregistry registry) { if (!this.resourceproperties.isaddmappings()) { logger.debug("default resource handling disabled"); } else { 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}); } }); }}
随后进入到getstaticlocations()方法可以发现变量 staticlocations 的取值如下:
classpath:/meta-inf/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
即项目运行时会到上述路径下寻找静态资源,也可以自定义静态资源路径,需在 application.properties 中配置:
spring.resources.static-locations=classpath:/folder1/,classpath:/folder2/
注:一旦自定义了静态文件夹的路径,则默认的静态资源路径就会失效。
2. 欢迎页静态资源路径下的 index.html 文件会被/**所映射,当访问http://localhost:8080/时 ,会默认映射到静态资源文件夹下的 index.html。
遇到的问题
新建 index.html 文件后运行项目,访问http://localhost:8080/时会页面错误:
控制台报如下错误:
spring boot 的版本是 2.7.8,tomcat 的版本是 9.0.71。spring boot 通过内嵌的 tomcat 来运行项目,但需要依靠本地的 java 环境,我本地的 java 版本是 java 1.8.0_261(即 java 8 版本),一般 java 8 和 tomcat 8.x.x 配套使用,这里可能是版本冲突导致的问题。将项目的 sdk 改为jbr-11 jetbrains runtime version 11.0.10即可解决问题:
jetbrains runtime 可以认为是 idea 自带的 java 运行环境。
以上就是springboot静态资源映射规则是什么的详细内容。