SpringBoot静态资源映射规则浅析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot静态资源映射规则浅析

哈密瓜Q   2023-03-23 我要评论

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 运行环境。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们