2

I have a main.js in thymeleaf template, each time I call it I want to add a version parameter so that it will not be cached and my latest changes will work.

    <script src="/main.js?version=345345456"></script>
</body>
</html>

Since it's the layout behind all other templates, I don't want to pass a variable from controllers.

So I decided to add a bean method to my application class

@SpringBootApplication
public class NexusApplication {

    @Bean
    public double jsVersion(){
        return Math.random();
    }

}

Than I added:

<script th:src="@{/js/my-script.js(version=NexusApplication.jsVersion())}"></script>

Output is:

<script th:src="@{/main.js?(version=NexusApplication.jsVersion())}"></script>

What am I missing? How should I approach this issue in a better way?

tolga
  • 2,462
  • 4
  • 31
  • 57

1 Answers1

3

One Java approach is to generate a random value using your method if you want, or see How do I generate random integers within a specific range in Java?, if you want an integer with a certain number of digits in it.

Then you can add that value (let's call it randNumber) to the template's model in the usual Spring way - for example:

model.addAttribute("randNumber", randNumber);

Now you can use the following in your Thymeleaf template:

<script th:src="@{/main.js(version=${randNumber})}"></script>

Note how the variable needs to be a Thymeleaf expression in ${...}.


One alternative approach, which may be acceptable is to use Thymeleaf's expression utility method for random alphanumeric strings:

${#strings.randomAlphanumeric(count)}

So, for example, for a string of length 5:

<script th:src="@{/main.js(version=${#strings.randomAlphanumeric(5)})}"></script>

You don't need any Java for this.

The end result would be similar to the first approach, but can contain characters as well as digits:

<script src="/main.js?version=2Q931"></script>
andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • Man...great, thank you. Thymeleaf's expression utility is the thing I was looking for. Thymeleaf's documentation is very weak so it's really very bloody to proceed for a new Java coder. – tolga Apr 04 '23 at 17:55