Tuesday 11 November 2014

Refresh the Browser Cache with Spring

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 front end, we will dig into Spring to knock out this behavior.

In development environment, Straight forward. I can say to 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-5.4.3.2/**"/>


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-5.4.3.2/app.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.

No comments:

Post a Comment