SpringBoot 靜態資源版本管理

來源:互聯網
上載者:User

在我們做Web開發時,免不了與靜態資源(css,js,images)打交道,通常的做法是在請求的URL上添加版本資訊,這樣可以很好的利用用戶端緩衝機制,只有當資源內容改變時,才需要從伺服器重新請求,並載入最新版本資源。 Spring的靜態資源管理 ResourceUrlProvider

首先,MVC中增加資源處理器

@Configurationpublic class MvcApplication extends WebMvcConfigurerAdapter {  @Override  public void addResourceHandlers(ResourceHandlerRegistry registry) {    VersionResourceResolver versionResourceResolver = new VersionResourceResolver()        .addVersionStrategy(new ContentVersionStrategy(), "/**");    registry.addResourceHandler("/javascript/*.js")        .addResourceLocations("classpath:/static/")        .setCachePeriod(60 * 60 * 24 * 365) /* one year */        .resourceChain(true)        .addResolver(versionResourceResolver);  }  ...}

在SpringBoot中就可以用如下配置

spring:  resources:    chain:      enabled: true      cache: true      version:        content:          enabled: true          paths: /static/**        fixed:          enabled: true          version: 1.0          paths: /js/**,/foo/**

或者

spring:  resources:    chain:      enabled: true      cache: true      version.content:        enabled: true        paths: /static/**      version.fixed:        enabled: true        version: 1.0        paths: /js/**,/foo/**

靜態資源路徑請根據實際路徑修改

**ContentVersionStrategy**MD5策略,如,請求

/javascript/test-69ea0cf3b5941340f06ea65583193168.js

則被解析為:

/javascript/test.js

FixedVersionStrategy固定版本原則,如

/v1.2.3/javascript/test.js

使用ResourceUrlProvider產生包含MD5資訊

With a ResourceUrlProvider a resource URL (e.g. /javascript/test.js) can be converted to a versioned URL (e.g. /javascript/test-69ea0cf3b5941340f06ea65583193168.js). A ResourceUrlProvider bean with the id mvcResourceUrlProvider is automatically declared with the MVC configuration.

如果你使用Thymeleaf模板引擎(可以直接存取ResourceUrlProvider Bean),那麼前端頁面你可以直接這麼使用:

<script type="application/javascript"        th:src="${@mvcResourceUrlProvider.getForLookupPath('/javascript/test.js')}"></script>

如果你使用其他例如FreeMarker等模板引擎,你可以通過@ControllerAdvice將ResourceUrlProvider Bean添加到Model Attribute中,就像這麼使用:

@ControllerAdvicepublic class ResourceUrlAdvice {  @Inject  ResourceUrlProvider resourceUrlProvider;  @ModelAttribute("urls")  public ResourceUrlProvider urls() {    return this.resourceUrlProvider;  }}

在這種情況下,前端頁面可以這麼寫

<script type="application/javascript"         th:src="${urls.getForLookupPath('/javascript/test.js')}"></script>

這種方式支援所有的模板引擎。 ResourceUrlEncodingFilter

另一種方式是通過ResourceUrlEncodingFilter,其是Servlet Filter,通過重寫HttpServletResponse.encodeURL()來產生版本化的資源地址。使用起來也很簡單,配置項中增加ResourceUrlEncodingFilter Bean,如下:

@SpringBootApplicationpublic class MvcApplication extends WebMvcConfigurerAdapter {  @Override  public void addResourceHandlers(ResourceHandlerRegistry registry) {    // same as before ..  }  @Bean  public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {    return new ResourceUrlEncodingFilter();  }  ...}

如果你正在使用的模板引擎(如:JSPs, Thymeleaf, FreeMarker and Velocity)支援直接調用response.encodeURL()方法,那麼版本資訊將自動被添加到資源URL中。

例如,在Thymeleaf中,我們可以用@{..} 文法

<script type="application/javascript" th:src="@{/javascript/test.js}"></script>

那麼最終頁面將會如下:

<script type="application/javascript"         src="/javascript/test-69ea0cf3b5941340f06ea65583193168.js"></script>

SpringBoot 1.3.0版本之後,使用* ResourceUrlEncodingFilter*將更加簡單

As of Spring Boot 1.3.0, this is now even easier. The Resource chain can be configured via Boot properties and the ResourceUrlEncodingFilter is automatically registered


Links to resources are rewritten at runtime in template, thanks to a ResourceUrlEncodingFilter, auto-configured for Thymeleaf and Velocity. You should manually declare this filter when using JSPs. Other template engines aren’t automatically supported right now, but can be with custom template macros/helpers and the use of the ResourceUrlProvider.

https://github.com/spring-projects/spring-boot/pull/3123

https://dzone.com/articles/2-step-resource-versioning-with-spring-mvc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.