Guide to automating the versioning of static assets (css, js, images) in a Java-based web application

To optimize the efficiency of browser cache usage for static files, I am seeking a way to always utilize cached content unless there has been a change in the file, in which case fetching the new content is necessary.

My goal is to append an md5 hash of the file to the virtual file path that the client sees. This could be done either as part of the directory or as part of the file name itself. By doing so, when the file undergoes changes, the client perceives it as a distinct resource.

I have knowledge of using a servlet filter to intercept requests containing the virtual file path and strip the md5 hash to reveal the actual file name within the directory structure.

In addition to this, I am interested in understanding if it's possible to use a filter to modify the apparent file name on the way out. Thus, give the impression to the client's browser that it is requesting the virtual file path without altering the real names or directory structures of the physical files themselves.

For instance:

Original file path = /css/1.css

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

Upon file modification:

Real file path = /css/1.css

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

Answer №1

For those utilizing Maven, consider incorporating the Minify Maven Plugin from here. Although not directly related to your current concern, this plugin allows you to merge the final names of your CSS/JS files with your application's version using ${version} (which can be configured in your imports). Whenever a new version of your application is built, new CSS/JS files are generated (based on the updated version number), prompting the browser to download them anew.

Here's an 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>
        <!-- Final CSS file -->
        <cssFinalFile>style.final.${version}.css</cssFinalFile>

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery computes the grand total without displaying it on the screen

I have been working on creating a small e-commerce website, and recently integrated a jQuery program to calculate items in the shopping cart. I wanted to display the total amount of these items next to the cart, but despite seeing that the calculation was ...

Incorporating a CSS file within a JSP page

I've been struggling to get my '.jsp' file to utilize a '.css' file that I created. Initially, I stored the '.css' file in the 'WEB-INF' folder but discovered that this folder is not accessible publicly. So, I m ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

What is the best way to compare two arrays of ids in MongoDB to find matching elements?

I have 2 arrays with different ids : bikesWithNoOrders [id , id1 , id2] filteredResult [id3 , id5] Is there a way to query and find all of them at once? This is what I currently have: queryBuilder.find({ _id: { $in: bikesWithNoOrders } }); queryBuilde ...

retrieving a map containing the values from an array using the `.includes()`

Currently, I am attempting to map my routes based on the roles they possess. For example, my mapped routes may have roles like ["User", "Admin"] or just ["Admin"]. The current user can have one or multiple roles assigned to them. This particular function w ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

Implementing an Ajax function for handling multiple button clicks

So, here's the situation - I've inherited a form with two buttons that inexplicably have the same name and id (seriously, don't ask me why, I didn't design this form haha). I'm attempting to utilize the Ajax .click function to trig ...

Arrange a series by the actual pixel width of the string

Imagine you have an array of tags represented as strings and you need to display them in a narrow view. Some tags are smaller, allowing for 2 to fit on one line, while larger tags require their own line. Your goal is to sort the array so that the smalles ...

A guide on merging existing data with fresh data in React and showcasing it simultaneously

As a newcomer to Reactjs, I am facing the following issue: I am trying to fetch and display new data as I scroll down Every time I scroll down, I fetch the data and save it in Redux. However, due to pagination, only 10 items are shown and not added to th ...

Keyboard access to the element is not possible

Having trouble uploading an image here, encountering the error mentioned below. Can anyone offer assistance? It's crucial. package kemgo_package; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.text ...

Check if the provided arguments in JavaScript are arrays and, if they are, combine them into a single large array

My array variables are as follows: const gumBrands = ['orbit', 'trident', 'chiclet', 'strident']; const mintBrands = ['altoids', 'certs', 'breath savers', 'tic tac']; Presen ...

Develop interactive div elements with the help of JavaScript/jQuery

Exploring dynamic div creation using javascript or jquery and looking for guidance. <div id="clickable"> <button class="start">Default</button> <button class="random">Randon</button> <button class="gradient"> ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Issues with angular-strap popover's onBeforeShow function not functioning as expected in Angular

I am currently utilizing the angular-strap popover feature. To learn more about it, visit According to the documentation, when an onBeforeShow function is provided, it should be called before the popover is displayed. However, I am experiencing issues wit ...

Having issues with referencing external JavaScript and CSS files in Angular 6

Dealing with an angular6 project and a bootstrap admin dashboard template, I'm facing issues importing the external js references into my Angular application. Looking for guidance on how to properly import and refer to external Js/CSS files in an angu ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

Having trouble extracting data from Moz Bar through selenium using Python?

Having trouble retrieving the spam score from Moz bar using Selenium WebDriver? I've attempted various methods such as XPath, class, and tag name without success. Any assistance would be greatly appreciated: from selenium.webdriver.common.by import By ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

Identify moving objects with react-beautiful-dnd

I've successfully implemented a draggable list using react-beautiful-dnd by following the tutorial. The result looked like this: You can find the code for this implementation here: https://github.com/DDavis1025/react-beautiful-dnd Now, I'm work ...