Spring boot2 thymeleaf JS / CSS version control

Springboot 2.2.0.RELEASE

1. Enable version control

By appending md5 code to the request js/css or manually adding version number to ensure that the content of js/css can be loaded by the browser in time when it changes:

yml configuration

spring:
  thymeleaf:
    mode: HTML
    cache: false
	resources:
    chain:
      strategy:
        content:
          enabled: true
          paths: /**
      enabled: true
      cache: false
    static-locations: classpath:/static/

or

java configuration

@Configuration
public class MvcInterceptorConfig implements WebMvcConfigurer {

    /**
     * Function description
     * <p>
     *    .addFixedVersionStrategy("v1.0.1", "/**") Add version number method for manual
     *    .addContentVersionStrategy("/**") md5 mode
     * </p>
     *
     * @param registry registry
     * @return void
     * @author wandoupeas
     * @date 2019-11-06
     * @since 2019-11-06
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .resourceChain(false)
                .addResolver(new VersionResourceResolver()
//                                     .addFixedVersionStrategy("v1.0.1", "/**")
                                     .addContentVersionStrategy("/**")
                );
    }
}

2. Tymeleaf page reference

When a normal abc.js browser is loaded, it will become abc-83fb8c4d9199dce0224da020642306f.js (MD5) or / v1.0.1/abc.js (add version number manually)

<!-- css Quote -->
<link th:href="@{/abc.css}" rel="stylesheet">
<link th:href="@{/css/def.css}" rel="stylesheet">

<!-- js Quote -->
<script th:src="@{/abc.js}"></script>
<script th:src="@{/js/def.js}"></script>

3.BUG repair

In general, the above methods can achieve the demand effect, but in the actual development process, the above configuration may not take effect due to relatively complex scenarios, which can be solved by adding the following beans

@SpringBootApplication
public class XxxApplication {

	public static void main(String[] args) {

		SpringApplication.run(XxxApplication.class, args);

	}

	/**
	 * Function description
	 * <p>
	 *    Add static resource md5 version control
	 * </p>
	 *
	 * @author wandoupeas
	 * @date 2019-11-06
	 * @since 2019-11-06
	 */
	@Bean
	public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
		return new ResourceUrlEncodingFilter();
	}
}

This article is written with OpenWrite

Keywords: Programming SpringBoot Spring Thymeleaf Java

Added by mrfruits on Wed, 06 Nov 2019 20:06:58 +0200