SpringBoot訪問靜態資源,配置和順序

今天在玩SpringBoot的demo的時候,放了張圖片在resources目錄下,啓動區訪問的時候,突然好奇是識別哪些文件夾來展示靜態資源的, 爲什麼有時候放的文件夾不能顯示,有的卻可以.

1. SpringBoot的默認配置

首先我們打開WebMvcAutoConfiguration類, 因爲是靜態資源的位置, 所以搜索location,找到這一行代碼:

 String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
      this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }

然後進入getStaticLocations這個方法,到了ResourceProperties類中的

  public String[] getStaticLocations() {
    return this.staticLocations;
  }

這個方法,那接着看staticLocations這個屬性,其實就到了這個類的頂部

public class ResourceProperties {
  private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
  private String[] staticLocations;
  private boolean addMappings;
  private final ResourceProperties.Chain chain;
  private final ResourceProperties.Cache cache;

  public ResourceProperties() {
    this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
    this.addMappings = true;
    this.chain = new ResourceProperties.Chain();
    this.cache = new ResourceProperties.Cache();
  }
...
}

可以看出,靜態資源默認的位置是classpath,也就是resource目錄下的:

  • /META-INF/resources
  • /resources
  • /static
  • /public

而且順序就是數組的順序.

2. 測試

我們創建一個index.html頁面,然後<h1>標籤分別是各自的路徑,比如在/META-INF/resources下的index.html:

<!DOCTYPE html >
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>http-template</title>
</head>
<body>
<h1 >META-INF.resources</h1>
</body>
</html>

在上面四個文件夾中各自放一個不同標題的頁面,啓動springboot,訪問localhost:8080
可以看到頁面的標題是/META-INF/resources, 說明是按照上面的默認配置讀取順序讀取的
在這裏插入圖片描述
注意,這裏不需要加這個靜態資源文件夾的名字!!,比如localhost:8080能看到頁面,但是localhost:8080/staticlocalhost:8080/META-INF/resources是訪問不了的

爲了繼續證實四個文件夾都可以,我放了同一個圖片在各自文件夾,只是名字不同,結構如下:
在這裏插入圖片描述
訪問

  • localhost:8080/2b.jpg
  • localhost:8080/3b.jpg
  • localhost:8080/4b.jpg
  • localhost:8080/5b.jpg

都能訪問(不需要加靜態資源文件夾的名字!!!), 反而是resource根目錄,也就是classpath下的1b.jpg不能訪問

3.配置

配置一: 是否可以訪問靜態資源

spring:
  mvc:
    static-path-pattern: /static/**

這個配置默認是/**, 表示的是正則匹配到這種路徑纔去訪問靜態資源,所以默認情況下,上面四個能夠訪問的路徑也必須加上/zgd纔可以訪問
另一個需要注意的事,默認情況下訪問index.html頁面,不需要加這個文件名,比如localhost:8080,但是配置了該項後,需要文件名.localhost:8080/zgd/index.html
在這裏插入圖片描述
加上index.html資源全稱後可以訪問
在這裏插入圖片描述

配置二: 去哪找靜態資源
這個配置就是我們上面說的那四個文件夾的配置了,註釋掉上面的配置,啓動看看

spring:
  resources:
    static-locations: classpath:/static/

啓動訪問localhost:8080
不出意料的顯示的是static的標題,也就是static文件夾下的html文件.
在這裏插入圖片描述
此時嘗試訪問3b.jpg,4b.jpb都是無法訪問的,只能訪問2b.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章