Ramesh
Ramesh

Reputation: 633

How to automate versioning of static files (css, js, image) in a Java web app

I want to use the browser cache of static files most efficiently, i.e. always use cached content, unless the file has changed, in which case get the new content.

I'd like to attach an md5 hash of the file to the virtual file path (either as a directory, or as part of the file name) the client sees, so that it when the file changes, the client thinks it is a different resource.

I know how to use a servlet filter to take a request containing that virtual file path and strip the md5 hash, and return the real file name in the directory structure.

Can I also use a filter to change the apparent file name on the way out, so that the client's browser thinks it is requesting the virtual file path, without changing the actual name or directory structure of my actual files?

For example:

real file path = /css/1.css

virtual file path = /static/1234/css/1.css

when the file changes

real file path = /css/1.css

virtual file path = /static/3451/css/1.css

Upvotes: 2

Views: 3337

Answers (1)

lgd
lgd

Reputation: 1212

If you are using Maven, you could add this great plugin : Minify Maven Plugin. It is not directly linked to your issue, but you can concatenante the final name of your CSS/JS files with the version of your application using ${version} (you should be able to do this in your imports). Everytime you will build a new version of your application, you should have new CSS/JS files (by the new version number) and force the browser to download it again.

Example :

<plugin>
    <groupId>com.samaxes.maven</groupId>
    <artifactId>minify-maven-plugin</artifactId>
    <version>1.7.4</version>
    <executions>
        <execution>
            <phase>prepare-package</phase>
            <goals>
                <goal>minify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <webappSourceDir>${basedir}/src/main/webapp/</webappSourceDir>
        <webappTargetDir>${basedir}/src/main/webapp/</webappTargetDir>
        <charset>UTF-8</charset>
        <cssSourceDir>css</cssSourceDir>
        <cssSourceFiles>
            <cssSourceFile>style.css</cssSourceFile>
        </cssSourceFiles>
        <cssTargetDir>css</cssTargetDir>
        <!-- Your final CSS file -->
        <cssFinalFile>style.final.${version}.css</cssFinalFile>

        <jsSourceDir>js</jsSourceDir>
        <jsSourceFiles>
            <jsSourceFile>script.js</jsSourceFile>
        </jsSourceFiles>
        <jsTargetDir>js</jsTargetDir>
        <!-- Your final JS file -->
        <jsFinalFile>script.final.${version}.js</jsFinalFile>
        <jsEngine>CLOSURE</jsEngine>
    </configuration>
</plugin>

Upvotes: 2

Related Questions