1. 程式人生 > 其它 >Web開發靜態資源處理

Web開發靜態資源處理

Web開發靜態資源處理

7. Web開發靜態資源處理

7.1 靜態資源處理

我們要引入前端資源,專案中有許多的靜態資源,比如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;
    }
    // webjars 配置
    addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
    // 靜態資源配置
    addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
        registration.addResourceLocations(this.resourceProperties.getStaticLocations());
        if (this.servletContext != null) {
            ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
            registration.addResourceLocations(resource);
        }
    });
}

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

7.2 webjars靜態資源

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

使用SpringBoot需要使用Webjars,我們可以去搜索一下,網站:https://www.webjars.org

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

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

匯入完畢,在 External Libraries 中去檢視webjars目錄結構,並訪問Jquery.js檔案!

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

7.3 匯入自己的靜態資源

如果專案中要是使用自己的靜態資源該怎麼匯入呢?

我們看下一行程式碼,我們去找staticPathPattern發現第二種對映規則 :/** , 訪問當前的專案任意資源,它會去找 resourceProperties 這個類,resourceProperties繼承了WebProperties類中的靜態內部類Resources我們可以點進去看一下分析:

resourceProperties類

//resourceProperties類中呼叫父類的getStaticLocations()
@Override
@DeprecatedConfigurationProperty(replacement = "spring.web.resources.static-locations")
public String[] getStaticLocations() {
    return super.getStaticLocations();
}

點選getStaticLocations(),進入WebProperties類的靜態內部類Resources

public static class Resources {

		private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
				"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

		/**
		 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
		 * /resources/, /static/, /public/].
		 */
		private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

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

Resources類中可以設定和靜態資源有關的引數,裡面指向了要去尋找資源的資料夾,即上面陣列的路徑,

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

"classpath:/META-INF/resources/"
"classpath:/resources/"  // 1
"classpath:/static/"     // 2
"classpath:/public/"     // 3

我們可以在resources根目錄下新建對應的資料夾,都可以存放我們的靜態檔案,

resources根目錄下新建資料夾static,在static目錄下建立一個test.js檔案,訪問 http://localhost:8080/test.js , 它就會去這些資料夾中尋找對應的靜態資原始檔

7.4 自定義靜態資源路徑

我們也可以自己通過在配置檔案application.properties中來指定靜態資原始檔的存放路徑,一旦自己定義了靜態資料夾的路徑,原來的自動配置就都會失效了!

spring.resources.static-locations=classpath:/aadzj/,classpath:/dengzj/

7.5 首頁處理

靜態資原始檔夾說完,我們繼續在WebMvcAutoConfiguration配置類中向下看原始碼!可以看到一個歡迎頁的對映,就是我們的首頁!

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

點進去getWelcomePage()繼續看

private Resource getWelcomePage() {
    for (String location : this.resourceProperties.getStaticLocations()) {
        Resource indexHtml = getIndexHtml(location);
        if (indexHtml != null) {
            return indexHtml;
        }
    }
    ServletContext servletContext = getServletContext();
    if (servletContext != null) {
        return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
    }
    return null;
}

private Resource getIndexHtml(String location) {
    return getIndexHtml(this.resourceLoader.getResource(location));
}

private Resource getIndexHtml(Resource location) {
    try {
        Resource resource = location.createRelative("index.html");
        if (resource.exists() && (resource.getURL() != null)) {
            return resource;
        }
    }
    catch (Exception ex) {
    }
    return null;
}

歡迎頁,靜態資原始檔夾下的所有 index.html 頁面,被 /** 對映。

比如我訪問 http://localhost:8080/ ,就會找靜態資原始檔夾下的 index.html

7.6 網站圖示

與其他靜態資源一樣,Spring Boot在配置的靜態資源位置查詢 favicon.ico,如果存在這樣的檔案,它將自動用作為應用程式的favicon。

1、關閉SpringBoot預設圖示

#關閉預設圖示,高版本的SpringBoot已經失效了
spring.mvc.favicon.enabled=false

2、自己放一個圖示在靜態資源目錄下命名為favicon.ico,比如 public 目錄下

3、清除瀏覽器快取!重新整理網頁,發現圖示已經變成自己的了!

本文來自部落格園,作者:小公羊,轉載請註明原文連結:https://www.cnblogs.com/aadzj/p/15636710.html