首頁  >  文章  >  Java  >  SpringBoot靜態資源映射規則是什麼

SpringBoot靜態資源映射規則是什麼

PHPz
PHPz轉載
2023-05-13 16:28:061203瀏覽

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/時會頁錯誤:

SpringBoot靜態資源映射規則是什麼

控制台封包如下錯誤:

SpringBoot靜態資源映射規則是什麼

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即可解決問題:

SpringBoot靜態資源映射規則是什麼

JetBrains Runtime 可以認為是IDEA 自帶的java 運行環境。

以上是SpringBoot靜態資源映射規則是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除