Refresh the Browser Cache Using Spring

DZone 's Guide to

Refresh the Browser Cache Using Spring

Trying to refresh your browser cache with Spring? It's easier than you think! Here's how to accomplish this simple feat.

Free Resource

Even in this ever evolving world of open source technologies, we often get into situation where we can't get simple things working. One such problem which developer face is 'Refreshing the browser cache to reload the JS and CSS'. It looks horrible when your website loads the new data without your UI changes and you have to convince your client to hit F5 in the browser. Sad thing is each browser has its own way of reloading the cache and as a poor developer, you have to find out that too!

Lets talk about the solution. As most of Java applications use Spring MVC for a front end, we will dig into Spring to knock out this behavior.

In a development environment, it's straight forward. I can say to the browser, "don’t cache stuff."  But In an actual production system, you’ll want to be a little more specific about what you want cached and not cached.

So how do we control the browser? We have to spoof the location of the resource and trick the browser into thinking it’s a brand new file – obviously not cached. Spring handles it quite nicely and i would recommend it for hassle free implementation.

Spring resource mapping can be used like this,

<mvc:resources location="/app/js/, classpath:/js/" mapping="/app/js-**"/>

For all requests that come in that have the URL pattern /js followed by anything, look for the resource in folder named app/js in the web root or in a jar on the classpath.

Now, when a web browser requests a resource called /js- will serve the app.js file from the same old location but since the browser doesn’t know that, it must download the app.js file regardless of whether or not a previous version was cached.

Now how can we make this mapping version dymanic. Spring SPEL comes into picture here.

<util:properties id='versionProperties' location='classpath:app.properties'/>
<context:property-placeholder properties-ref="versionProperties"/>
<mvc:resources location="/app/js/, classpath:/js/" mapping="/app/js-${app.label}/**"/>

Since your app label will change every time you migrate to production, the above code will instruct the browser to reload its cache.

integration, spring, webdev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}