DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Customer 360: Fraud Detection in Fintech With PySpark and ML
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Coding
  3. Frameworks
  4. 2-Step Resource Versioning With Spring MVC

2-Step Resource Versioning With Spring MVC

These two simple steps will allow you to configure versioned resource URLs in Spring MVC, allowing the browser to cache resources for an unlimited time and update version info on the URL when a resource is changed.

By 
Michael Scharhag user avatar
Michael Scharhag
·
Sep. 22, 15 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.4K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Spring Framework

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!