最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中的靜態(tài)資源訪問的實現(xiàn)

 更新時間:2020年09月14日 14:48:15   作者:java-gubin  
這篇文章主要介紹了SpringBoot中的靜態(tài)資源訪問的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、說在前面的話

我們之間介紹過SpringBoot自動配置的原理,基本上是如下:

xxxxAutoConfiguration:幫我們給容器中自動配置組件;
xxxxProperties:配置類來封裝配置文件的內(nèi)容;

二、靜態(tài)資源映射規(guī)則

1、對哪些目錄映射?

classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:當前項目的根路徑

2、什么意思?

就我們在上面五個目錄下放靜態(tài)資源(比如:a.js等),可以直接訪問(http://localhost:8080/a.js),類似于以前web項目的webapp下;放到其他目錄下無法被訪問。

3、為什么是那幾個目錄?

3.1、看源碼

我們一起來讀下源碼,這個是SpringBoot自動配置的WebMvcAutoConfiguration.java類來幫我們干的。

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  if (!this.resourceProperties.isAddMappings()) {
    logger.debug("Default resource handling disabled");
    return;
  }
  Integer cachePeriod = this.resourceProperties.getCachePeriod();
  if (!registry.hasMappingForPattern("/webjars/**")) {
    customizeResourceHandlerRegistration(
        registry.addResourceHandler("/webjars/**")
            .addResourceLocations(
                "classpath:/META-INF/resources/webjars/")
        .setCachePeriod(cachePeriod));
  }
  String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  if (!registry.hasMappingForPattern(staticPathPattern)) {
    customizeResourceHandlerRegistration(
        registry.addResourceHandler(staticPathPattern)
            .addResourceLocations(
                this.resourceProperties.getStaticLocations())
        .setCachePeriod(cachePeriod));
  }
}

3.2、分析源碼

我們重點分析后半截,前半截后面會介紹。

// staticPathPattern是/**
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
  customizeResourceHandlerRegistration(
      registry.addResourceHandler(staticPathPattern)
          .addResourceLocations(
              this.resourceProperties.getStaticLocations())
      .setCachePeriod(cachePeriod));
}
this.resourceProperties.getStaticLocations()
========>
ResourceProperties
public String[] getStaticLocations() {
  return this.staticLocations;
}
========>
private String[] staticLocations = RESOURCE_LOCATIONS;
========>
private static final String[] RESOURCE_LOCATIONS;
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
      "classpath:/META-INF/resources/", "classpath:/resources/",
      "classpath:/static/", "classpath:/public/" };
========>
static {
  // 可以看到如下是對上面兩個數(shù)組進行復(fù)制操作到一個新數(shù)組上,也就是合并。
  RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
      + SERVLET_RESOURCE_LOCATIONS.length];
  System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
      SERVLET_RESOURCE_LOCATIONS.length);
  System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
      SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
}
所以上述代碼經(jīng)過我的翻譯后成為了如下樣子:

registry.addResourceHandler("/**").addResourceLocations(
  "classpath:/META-INF/resources/", "classpath:/resources/",
      "classpath:/static/", "classpath:/public/", "/")
  // 設(shè)置緩存時間
  .setCachePeriod(cachePeriod));

3.3、一句話概括

WebMvcAutoConfiguration類自動為我們注冊了如下目錄為靜態(tài)資源目錄,也就是說直接可訪問到資源的目錄。

classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:當前項目的根路徑

優(yōu)先級從上到下。

所以,如果static里面有個index.html,public下面也有個index.html,則優(yōu)先會加載static下面的index.html,因為優(yōu)先級!

4、默認首頁

PS:就是直接輸入ip:port/項目名稱默認進入的頁面。

4.1、看源碼

WebMvcAutoConfiguration.java

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
   ResourceProperties resourceProperties) {
  return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
     this.mvcProperties.getStaticPathPattern());
}

4.2、分析源碼

resourceProperties.getWelcomePage()
========>
public Resource getWelcomePage() {
  // 遍歷默認靜態(tài)資源目錄后面拼接個index.html的數(shù)組
  // 比如:[/static/index.html, /public/index.html等等]
  for (String location : getStaticWelcomePageLocations()) {
    Resource resource = this.resourceLoader.getResource(location);
    try {
      if (resource.exists()) {
        resource.getURL();
        return resource;
      }
    }
    catch (Exception ex) {
      // Ignore
    }
  }
  return null;
}
========>
// 下面這段代碼通俗易懂,就是給默認靜態(tài)資源目錄后面拼接個index.html并返回,比如:/static/index.html
private String[] getStaticWelcomePageLocations() {
  String[] result = new String[this.staticLocations.length];
  for (int i = 0; i < result.length; i++) {
    String location = this.staticLocations[i];
    if (!location.endsWith("/")) {
      location = location + "/";
    }
    result[i] = location + "index.html";
  }
  return result;
}

所以上述代碼經(jīng)過我的翻譯后成為了如下樣子:

return new WelcomePageHandlerMapping(
  "classpath:/META-INF/resources/index.html",
  "classpath:/resources/index.html",
  "classpath:/static/index.html",
  "classpath:/public/index.html",
  "/index.html"
  , "/**");

4.3、一句話概括

WebMvcAutoConfiguration類自動為我們注冊了如下文件為默認首頁。

classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html 
classpath:/public/index.html
/index.html

優(yōu)先級從上到下。

所以,如果static里面有個index.html,public下面也有個index.html,則優(yōu)先會加載static下面的index.html,因為優(yōu)先級!

5、favicon.ico

PS:就是這個圖標。

5.1、看源碼

@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {

  private final ResourceProperties resourceProperties;

  public FaviconConfiguration(ResourceProperties resourceProperties) {
   this.resourceProperties = resourceProperties;
  }

  @Bean
  public SimpleUrlHandlerMapping faviconHandlerMapping() {
   SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
   mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
   mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
      faviconRequestHandler()));
   return mapping;
  }

  @Bean
  public ResourceHttpRequestHandler faviconRequestHandler() {
   ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
   requestHandler
      .setLocations(this.resourceProperties.getFaviconLocations());
   return requestHandler;
  }

}

5.2、分析源碼

// 首先可以看到的是可以設(shè)置是否生效,通過參數(shù)spring.mvc.favicon.enabled來配置,若無此參數(shù),則默認是生效的。
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
========》
// 可以看到所有的**/favicon.ico都是在faviconRequestHandler()這個方法里找。
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
========》
faviconRequestHandler().this.resourceProperties.getFaviconLocations()
// 就是之前的五個靜態(tài)資源文件夾。  
List<Resource> getFaviconLocations() {
  List<Resource> locations = new ArrayList<Resource>(
      this.staticLocations.length + 1);
  if (this.resourceLoader != null) {
    for (String location : this.staticLocations) {
      locations.add(this.resourceLoader.getResource(location));
    }
  }
  locations.add(new ClassPathResource("/"));
  return Collections.unmodifiableList(locations);
}

5.3、一句話概括

只要把favicon.ico放到如下目錄下,就會自動生效。

classpath:/META-INF/resources/ 
classpath:/resources/
classpath:/static/ 
classpath:/public/
/:當前項目的根路徑

6、webjars

6.1、看源碼

WebMvcAutoConfiguration

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  if (!this.resourceProperties.isAddMappings()) {
    logger.debug("Default resource handling disabled");
    return;
  }
  Integer cachePeriod = this.resourceProperties.getCachePeriod();
  if (!registry.hasMappingForPattern("/webjars/**")) {
    customizeResourceHandlerRegistration(
        registry.addResourceHandler("/webjars/**")
            .addResourceLocations(
                "classpath:/META-INF/resources/webjars/")
        .setCachePeriod(cachePeriod));
  }
  String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  if (!registry.hasMappingForPattern(staticPathPattern)) {
    customizeResourceHandlerRegistration(
        registry.addResourceHandler(staticPathPattern)
            .addResourceLocations(
                this.resourceProperties.getStaticLocations())
        .setCachePeriod(cachePeriod));
  }
}

6.2、分析源碼

這次我們來分析前半截。

Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
  customizeResourceHandlerRegistration(
      registry.addResourceHandler("/webjars/**")
          .addResourceLocations(
              "classpath:/META-INF/resources/webjars/")
      .setCachePeriod(cachePeriod));
}

6.3、一句話概括

所有/webjars/**都從classpath:/META-INF/resources/webjars/路徑下去找對應(yīng)的靜態(tài)資源。

6.4、什么是webjars?

就是以jar包的方式引入靜態(tài)資源。

官網(wǎng)地址:http://www.webjars.org/。類似于maven倉庫。

我們可以做個例子,將jquery引入到項目中

<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>jquery</artifactId>
  <version>3.3.1</version>
</dependency>

看項目依賴

會自動為我們引入jquery,要怎么使用呢?我們上面說過:

所有/webjars/*都從classpath:/META-INF/resources/webjars/路徑下去找對應(yīng)的靜態(tài)資源。

所以我們啟動項目,訪問:http://localhost:8080/webjars/jquery/3.3.1/jquery.js即可。

必須在這幾個路徑下SpringBoot才會掃描到!

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑

到此這篇關(guān)于SpringBoot中的靜態(tài)資源訪問的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot 靜態(tài)資源訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java 獲取原始請求域名實現(xiàn)示例

    Java 獲取原始請求域名實現(xiàn)示例

    這篇文章主要為大家介紹了Java 獲取原始請求域名實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • SpringBoot POST請求接收多個參數(shù)值為null問題

    SpringBoot POST請求接收多個參數(shù)值為null問題

    SpringBoot接口中POST請求接收JSON數(shù)據(jù)時,使用簡單類型接收會報null,需要封裝成實體類或使用Map(并注明泛型)接收,并且使用@RequestBody注解
    2025-02-02
  • Spring Bean的定義概念和使用

    Spring Bean的定義概念和使用

    這篇文章主要介紹了Spring Bean的定義概念和使用,Spring bean對象是構(gòu)成應(yīng)用程序的支柱,也是由Spring IoC容器管理的。bean是一個被實例化,組裝,并通過Spring IoC容器所管理的對象。這些bean是由用容器提供的配置元數(shù)據(jù)創(chuàng)建的
    2023-04-04
  • Java抽象類和接口使用梳理

    Java抽象類和接口使用梳理

    對于面向?qū)ο缶幊虂碚f,抽象是它的一大特征之一,在?Java?中可以通過兩種形式來體現(xiàn)OOP的抽象:接口和抽象類,下面這篇文章主要給大家介紹了關(guān)于Java入門基礎(chǔ)之抽象類與接口的相關(guān)資料,需要的朋友可以參考下
    2022-02-02
  • Java中使用BigDecimal進行浮點數(shù)運算

    Java中使用BigDecimal進行浮點數(shù)運算

    這篇文章主要介紹了Java中使用BigDecimal進行浮點數(shù)運算,需要的朋友可以參考下
    2014-07-07
  • Java大文件上傳詳解及實例代碼

    Java大文件上傳詳解及實例代碼

    這篇文章主要介紹了Java大文件上傳詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • springboot+spring?data?jpa實現(xiàn)新增及批量新增方式

    springboot+spring?data?jpa實現(xiàn)新增及批量新增方式

    這篇文章主要介紹了springboot+spring?data?jpa實現(xiàn)新增及批量新增方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 總結(jié)Java常用的時間相關(guān)轉(zhuǎn)化

    總結(jié)Java常用的時間相關(guān)轉(zhuǎn)化

    今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著Java常用的時間相關(guān)轉(zhuǎn)化展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • SpringBoot通過@Value實現(xiàn)給靜態(tài)變量注入值詳解

    SpringBoot通過@Value實現(xiàn)給靜態(tài)變量注入值詳解

    這篇文章主要介紹了springboot如何通過@Value給靜態(tài)變量注入值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Java使用RedisTemplate操作Redis遇到的坑

    Java使用RedisTemplate操作Redis遇到的坑

    這篇文章主要介紹了Java使用RedisTemplate操作Redis遇到的坑,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12

最新評論

万全县| 儋州市| 桦川县| 武功县| 泰来县| 浦北县| 漳州市| 连山| 闽侯县| 贵溪市| 新沂市| 英德市| 黄浦区| 庄浪县| 宁安市| 宁晋县| 南皮县| 伊吾县| 古浪县| 岗巴县| 南乐县| 锦州市| 苏尼特右旗| 嘉鱼县| 辽宁省| 吉隆县| 大余县| 白朗县| 宝鸡市| 泸西县| 黄平县| 金门县| 宁南县| 赫章县| 西和县| 大化| 宝坻区| 长子县| 赣州市| 巴林右旗| 南乐县|