首页 > 文章列表 > SpringBoot静态资源映射规则是什么

SpringBoot静态资源映射规则是什么

springboot
446 2023-05-13

SpringBoot静态资源映射规则是什么

1. 静态资源映射规则

在项目中双击shiftctrl+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 运行环境。