When serving static resources, it is common practice to append some kind of version information to the resource URL. This allows the browser to cache resources for an unlimited time. Whenever the content of the resource is changed, the version information in the URL is changed too. The updated URL forces the client browser to discard the cached resource and reload the latest resource version from the server.
With Spring it only takes two simple steps to configure versioned resource URLs. In this post we will see how it works.
Serving versioned URLs
First we need to tell Spring that resources should be accessible via a versioned URL. This is done in the resource handler MVC configuration:
@Configuration public 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); } ... }
Here we create a resource handler for JavaScript files located in folder named static inside the classpath. The cache period for these JavaScript files is set to one year. The important part is the VersionResourceResolver which supports resource URLs with version information. A VersionStrategy is used to obtain the actual version for a resource.
In this example we use a ContentVersionStrategy. This VersionStrategy implementation calculates an MD5 hash from the content of the resource and appends it to the file name.
For example: Assume we have a JavaScript file test.js inside the classpath:/static/ directory. The MD5 hash for test.js is 69ea0cf3b5941340f06ea65583193168.
We can now send a request to
/javascript/test-69ea0cf3b5941340f06ea65583193168.js
which will resolve to classpath:/static/test.js.
Note that it is still possible to request the resource without the MD5 hash. So this request works too:
/javascript/test.js
An alternative VersionStrategy implementation is FixedVersionStrategy. FixedVersionStrategy uses a fixed version string that added as prefix to the resource path.
For example:
/v1.2.3/javascript/test.js
Generating versioned URLs
Now we need to make sure the application generates resource URLs that contain the MD5 hash.
One approach for this is to use a ResourceUrlProvider. 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.
In case you are using Thymeleaf as template engine, you can access the ResourceUrlProvider bean directly from templates using the @bean syntax.
For example:
<script type="application/javascript" th:src="${@mvcResourceUrlProvider.getForLookupPath('/javascript/test.js')}"> </script>
If you are using a template engine which does not give you direct access to Spring beans, you can add the ResourceUrlProvider bean to the model attributes. Using a ControllerAdvice, this might look like this:
@ControllerAdvice public class ResourceUrlAdvice { @Inject ResourceUrlProvider resourceUrlProvider; @ModelAttribute("urls") public ResourceUrlProvider urls() { return this.resourceUrlProvider; } }
Inside the view we can then access the ResourceUrlProvider using the urls model attribute:
<script type="application/javascript" th:src="${urls.getForLookupPath('/javascript/test.js')}"> </script>
This approach should work with all template engines that support method calls.
An alternative approach to generate versioned URLs is the use of ResourceUrlEncodingFilter. This is a Servlet Filter that overrides the HttpServletResponse.encodeURL() method to generate versioned resource URLs.
To make use of the ResourceUrlEncodingFilter we simply have to add an additional bean to our configuration class:
@SpringBootApplication public class MvcApplication extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // same as before .. } @Bean public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { return new ResourceUrlEncodingFilter(); } ... }
If the template engine you are using calls the response encodeURL() method, the version information will be automatically added to the URL. This will work in JSPs, Thymeleaf, FreeMarker and Velocity.
For example: With Thymeleaf we can use the standard @{..} syntax to create URLs:
<script type="application/javascript" th:src="@{/javascript/test.js}"></script>
This will result in:
<script type="application/javascript" src="/javascript/test-69ea0cf3b5941340f06ea65583193168.js"> </script>
Summary
Adding version information to resource URLs is a common practice to maximize browser caching. With Spring we just have to define a VersionResourceResolver and a VersionStrategy to serve versioned URLs. The easiest way to generate versioned URLs inside template engines, is the use of an ResourceUrlEncodingFilter.
If the standard VersionStrategy implementations do not match your requirements, you can create our own VersionStrategy implementation.
You can find the full example source code on GitHub.
Comments
Josemi - Tuesday, 22 September, 2015
Very interesting approach. I've Angular and now I'm trying tó find a way tó find nnect your solution with it. Any advice Will be wellcome :-)
Michael - Thursday, 24 September, 2015
Nice! What does this look like using a Freemarker template, though?
Paris - Thursday, 12 November, 2015
The annotations are a little different form the first example to the second. The first has a '@Configuration' tag. The other has a '@SpringBootApplication', but doesnt include the first. Is this on purpose?
Peter - Wednesday, 2 March, 2016
Great article.
th:src="${@mvcResourceUrlProvider.getForLookupPath('/javascript/test.js')}"
I think should be:
th:src="@{ ${@mvcResourceUrlProvider.getForLookupPath('/javascript/test.js')} }"
in order to get "correct" handling of resources based on context set in thymeleaf
Fatema Jeenwala - Monday, 7 March, 2016
What is the syntax for velocity template. I did a lot of google search, but couldn't find it.
Louie - Sunday, 8 May, 2016
Great Article! Saved me some serious time
Enes - Saturday, 26 November, 2016
Thanks a lot for the information!
mahesh - Wednesday, 15 July, 2020
Thanks it helped me.
But in development time eclipse tomcat server code auto publish mode, when change in Javascript files those changes are not reflecting in the browser.
How can i resolve this
PravinP - Sunday, 30 May, 2021
This approach is easy to do and can be done with minimal code changes.
but causes problems if you are in a environment with NGINX as a web server caching static resources. As NGINX does not recognize the versioned url and responds to browser with a 404.
if there was an option of adding a 'version' parameter to URL, this would fix this problem.
Leave a reply