Java Web Application: Force static content (js, css, html) to load if modified file is modified

We are trying to force the client browser to reload static files when they change. We currently have build scripts that automatically create a new directory with a build time stamp and replace the content in the code to point to that directory.

However, I believe that this is hardly the optimal solution. This forces the client browser to download every single file if a new assembly exists, even if only one file is changed, and the build time increases significantly by scanning each file and replacing every static file reference.

I know we can also set the version when we declare files (something like <link src = "blahblah.css? Version = 1.1" / ">), but that forces us to change all of our code to include the placeholder for the version and there are still our build scripts replacing it.

Is there a smarter way to do this? We are using Spring MVC. Is there any option in mvc: resources that I don't know to do this without changing the code? Or something in web.xml?

We are using tomcat. Is there a way to do this at the server level? Would it help to use cache like varnish or something else? Or do these caches allow you to set an expiration time and not check if the file has changed? Please be aware that I am not comfortable doing server and cache configuration tasks.

I found out about this project https://code.google.com/p/modpagespeed/

, but since it is far from my comfort zone I am struggling to understand the possibilities and if it helps with what I want.

Does anyone have any idea? Thanks to

+3


source to share


2 answers


You can use version as query parameter eg. /resources/foo.js?_version=1.0.0

... If you are using Maven it is difficult to get version information from /META-INF/maven/{groupId}/{artifactId}/pom.properties

. Of course, this will force all scripts to be reloaded with each new version ... but probably new versions are probably not deployed often.



Then it's always a good idea to configure the HTTP cache headers correctly. <mvc:resources>

should handle the header correctly Last-Modified

for you. And you can set thecache-period

browser to watch resource changes more often.

+2


source


Here is a working solution: CorrectBrowserCacheHandlerFilter.java

Basically, when your browser requests static files, the server redirects all requests to the same one, but with a hash request parameter (for example ?v=azErT

) that depends on the content of the target static file.



By doing this, the browser will never cache static files declared in your index.html

for example (because it will always receive 302 Moved Temporarily

), but will only cache those that have a hash version (the server will respond 200

for them). This way the browser cache will be efficiently used for those static hash versioned files.

Disclaimer: I am the author CorrectBrowserCacheHandlerFilter.java

.

0


source







All Articles