简体   繁体   中英

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. eg

<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.

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

@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Value("${resources}")
    private String resources;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

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

}

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 application.properties is below

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

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

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/tmp/resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM