從源碼分析Spring Boot靜態資源映射規則(以圖說話)

寫在前面:
環境:Spring Boot版本:1.5.10.RELEASE
文章中相關源碼的分析,都是以WebMvcAutoConfiguration類爲起點,在其基礎上再進行相關的分析。

一、訪問/webjars/**路徑

	  public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Integer cachePeriod = this.resourceProperties.getCachePeriod();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
                }
            }
        }

從源碼可知,所有/webjars/**的請求都會到"classpath:/META-INF/resources/webjars/"路徑下尋找相關的資源。
這裏解釋一下,所謂的webjars即是以jar包的方式引入靜態資源。

開發時,我們所需的一些前端資源可以到webjars官網以maven的方式進行引入。
這裏以引入jquery爲例進行演示:

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

引入jquery依賴後,我們在External Libraries下找到如下的結構圖。
在這裏插入圖片描述
我們在瀏覽器地址欄輸入localhost:8080/webjars/jquery/3.3.1/jquery.js將會看到jquery.js的代碼。
溫馨提示:如果在application.properties中配置server.context-path=/crud路徑後,我們在訪問的時候需要添加/crud,如:http://localhost:8080/crud/webjars/jquery/3.3.1/jquery.js
在這裏插入圖片描述

二、訪問/**路徑

在這裏插入圖片描述
在這裏插入圖片描述
經上述分析,/**訪問當前項目的任何資源,都去(靜態資源的文件夾)找映射,如下:

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

現有靜態資源放在static目錄下,我們可以訪問http://localhost:8080/asserts/js/Chart.min.js
在這裏插入圖片描述
在這裏插入圖片描述

三、訪問/**路徑下的歡迎頁

在這裏插入圖片描述
在這裏插入圖片描述
首頁(index.html)可以存放的位置爲靜態資源存放的位置。如下
在這裏插入圖片描述

四、訪問**/favicon.ico路徑

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(-2147483647);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
                return mapping;
            }

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

在這裏插入圖片描述
經上分析,favicon.ico存放的位置依然爲靜態資源文件的路徑下。

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