SpringBoot Web開發靜態資源處理

Web開發探究

簡介

其實SpringBoot的東西用起來非常簡單,因爲SpringBoot最大的特點就是自動裝配

使用SpringBoot的步驟:

1、創建一個SpringBoot應用,選擇我們需要的模塊,SpringBoot就會默認將我們的需要的模塊自動配置

2、手動在配置文件中配置部分配置項目就可以運行起來了

3、專注編寫業務代碼,不需要考慮以前那樣一大堆的配置了。

要熟悉掌握開發,之前學習的自動配置的原理一定要搞明白!

比如SpringBoot到底幫我們配置了什麼?我們能不能修改?我們能修改哪些配置?我們能不能擴展?

  • 向容器中自動配置組件 :*** Autoconfiguration
  • 自動配置類,封裝配置文件的內容:***Properties

靜態資源處理

靜態資源映射規則

首先,我們搭建一個普通的SpringBoot項目,回顧一下HelloWorld程序!

寫請求非常簡單,那我們要引入我們前端資源,我們項目中有許多的靜態資源,比如css,js等文件,這個SpringBoot怎麼處理呢?

如果我們是一個web應用,我們的main下會有一個webapp,我們以前都是將所有的頁面導在這裏面的,對吧!但是我們現在的pom呢,打包方式是爲jar的方式,那麼這種方式SpringBoot能不能來給我們寫頁面呢?當然是可以的,但是SpringBoot對於靜態資源放置的位置,是有規定的!

我們先來聊聊這個靜態資源映射規則:

  • SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 這個配置類裏面;

  • 我們可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;

  • 有一個方法:addResourceHandlers 添加資源處理

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!this.resourceProperties.isAddMappings()) {
            // 已禁用默認資源處理
            logger.debug("Default resource handling disabled");
            return;
        }
        // 緩存控制
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        // webjars 配置
        if (!registry.hasMappingForPattern("/webjars/**")) {
            customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                                 .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                                 .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }
        // 靜態資源配置
        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                                 .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                                 .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }
    }
    •  

    讀一下源代碼:比如所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找對應的資源;

什麼是webjars 呢?

Webjars本質就是以jar包的方式引入我們的靜態資源 , 我們以前要導入一個靜態資源文件,直接導入即可。

第一種靜態資源映射規則

使用SpringBoot需要使用Webjars,我們可以去搜索一下:

網站:https://www.webjars.org

要使用jQuery,我們只要要引入jQuery對應版本的pom依賴即可!

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

導入完畢,查看webjars目錄結構,並訪問Jquery.js文件!

訪問:只要是靜態資源,SpringBoot就會去對應的路徑尋找資源,我們這裏訪問:http://localhost:8080/webjars/jquery/3.4.1/jquery.js

第二種靜態資源映射規則(常用)

1、那我們項目中要是使用自己的靜態資源該怎麼導入呢?我們看下一行代碼;

2、我們去找staticPathPattern發現第二種映射規則 :/** , 訪問當前的項目任意資源,它會去找 resourceProperties 這個類,我們可以點進去看一下分析:

// 進入方法
public String[] getStaticLocations() {
    return this.staticLocations;
}
// 找到對應的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路徑
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
    "classpath:/META-INF/resources/",
  	"classpath:/resources/", 
    "classpath:/static/", 
    "classpath:/public/" 
};

 

3、ResourceProperties 可以設置和我們靜態資源有關的參數;這裏面指向了它會去尋找資源的文件夾,即上面數組的內容。

4、所以得出結論,以下四個目錄存放的靜態資源可以被我們識別:

"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"

5、我們可以在resources根目錄下新建對應的文件夾,都可以存放我們的靜態文件;

6、比如我們訪問 http://localhost:8080/1.js , 他就會去這些文件夾中尋找對應的靜態資源文件;

自定義靜態資源路徑(知道這種方式就行一般不會用)

我們也可以自己通過配置文件來指定一下,哪些文件夾是需要我們放靜態資源文件的,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/ss/

總結

  1. 在springboot,我們可以使用以下方式處理靜態資源
    • webjars localhost:8080/webjars/
    • public,static,/**,resources localhost:8080/
  2. 優先級:resources > static(默認) > public

首頁處理

靜態資源文件夾說完後,我們繼續向下看源碼!可以看到一個歡迎頁的映射,就是我們的首頁!

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
                                                           FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
        this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
    return welcomePageHandlerMapping;
}

點進去繼續看

private Optional<Resource> getWelcomePage() {
    String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
    // ::是java8 中新引入的運算符
    // Class::function的時候function是屬於Class的,應該是靜態方法。
    // this::function的funtion是屬於這個對象的。
    // 簡而言之,就是一種語法糖而已,是一種簡寫
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
// 歡迎頁就是一個location下的的 index.html 而已
private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

 

截圖說明

  • 歡迎頁,靜態資源文件夾下的所有 index.html 頁面;被 /** 映射。

  • 比如我訪問 http://localhost:8080/ ,就會找靜態資源文件夾下的 index.html

  • 新建一個 index.html ,在我們上面的3個目錄( public,static,resources)中任意一個;然後訪問測試 http://localhost:8080/ 看結果!

1、關於網站圖標說明

歡迎頁面(Welcome Page)

Spring Boot supports both static and templated welcome pages. It first looks for an index.html file in the configured static content locations. If one is not found, it then looks for an index template. If either is found, it is automatically used as the welcome page of the application.

自定義應用圖標(Custom Facicon)

Spring Boot looks for a favicon.ico in the configured static content locations and the root of the classpath (in that order). If such a file is present, it is automatically used as the favicon of the application.

2、首頁圖標

2.2.x之前的版本(如2.1.7)springboot是這樣

與其他靜態資源一樣,Spring Boot在配置的靜態內容位置中查找 favicon.ico。如果存在這樣的文件,它將自動用作應用程序的favicon。

  1. 關閉SpringBoot默認圖標

    #關閉默認圖標
    spring.mvc.favicon.enabled=false
  2. 自己放一個圖標在靜態資源目錄下,我放在 public 目錄下

  3. 清除瀏覽器緩存Ctrl + F5!刷新網頁,發現圖標已經變成自己的了!

2.2.x之後的版本(如2.3.0)直接執行2和3就可以了

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