stove stove - 2 years ago 283
JSON Question

load js from filesystem into spring boot jar application (with thymeleaf)

I have kind of a utility made with spring boot with bundled tomcat packaged into executable jar.
what i need is to have some js (or possibly json) files in the same folder as the jar file and be able to insert them into the thymeleaf template.

<script type="text/javascript" src="somepath/myfile.js"></script>

I have managed to do this so far:
In controller:

String userDir = System.getProperty("user.dir");
model.addAttribute("userDir", "file://"+userDir+"/");

In template:

<script type="text/javascript" th:src="${userDir + 'myfile.js'}"></script>

at this moment I am able to see the code inside myfile.js via firebug html view, but not in scripts tab, nor the script is executed (any variable defined in this file is undefined).

How to do it?

I know I can create a json file and process it via java, but if solution I am searching for exists, Its much simpler and more convenient for me to use, moreover that way I can use custom js, not only json.

I also know this would be very unsafe in many cases, but in this case the app doesn't have to be safe at all, no matter what one wants to inject via the files.

Answer Source

You can customize the WebMvcConfigurationAdapter to add some file system folder to resource registry.

public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    private String resources;

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        if (resources != null) {
            registry.addResourceHandler("/myresources/**").addResourceLocations("file:" + resources);


then provide --resources parameter when you are executing the jar. Please note trailing /

java -jar your_jar_file --resources=/path/to/resources/

Also note that resources from this path are registered against /myresources/ path so you need to modify your template as below

<script type="text/javascript" src="myresources/myfile.js"></script>

myfile.js should be present in path mentioned in --resources parameter

Update #1 (I have not tested this but you can try)

Just found that spring boot supports a property to customize the static locations

Refer Spring Common Properties Appendix

The Property you need to define in is below


Append your locations to it. You can use file resource also like

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download