[英]Spring boot and Thymeleaf application: jquery is loading but not executing
[英]load js from filesystem into spring boot jar application (with thymeleaf)
我有一種使用spring boot制作的實用程序,捆綁了tomcat並打包到可執行jar中。 我需要的是在與jar文件相同的文件夾中有一些js(或可能是json)文件,並能夠將它們插入到thymeleaf模板中。 例如
<script type="text/javascript" src="somepath/myfile.js"></script>
到目前為止,我已經做到了:在控制器中:
String userDir = System.getProperty("user.dir");
model.addAttribute("userDir", "file://"+userDir+"/");
在模板中:
<script type="text/javascript" th:src="${userDir + 'myfile.js'}"></script>
目前,我可以通過Firebug html視圖查看myfile.js中的代碼,但無法在“腳本”選項卡中看到,也沒有執行腳本(此文件中定義的任何變量都是未定義的)。
怎么做?
我知道我可以創建一個json文件並通過java處理它,但是如果我正在尋找的解決方案存在,那么它對我來說將更簡單,更方便,而且這樣我不僅可以使用json,還可以使用自定義js。
我也知道在很多情況下這是非常不安全的,但是在這種情況下,無論人們想要通過文件注入什么內容,該應用程序都不必完全安全。
您可以自定義WebMvcConfigurationAdapter,以將一些文件系統文件夾添加到資源注冊表。
@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);
}
}
然后在執行jar時提供--resources參數。 請注意尾隨/
java -jar your_jar_file --resources = / path / to / resources /
另請注意,該路徑中的資源已針對/ myresources /路徑進行了注冊,因此您需要按如下所示修改模板
<script type="text/javascript" src="myresources/myfile.js"></script>
myfile.js應該出現在--resources參數中提到的路徑中
更新#1(我尚未測試過,但是您可以嘗試)
剛剛發現spring boot支持一個屬性以自定義靜態位置
請參閱Spring通用屬性附錄
您需要在application.properties中定義的屬性如下
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
附加您的位置。 您也可以使用文件資源
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/tmp/resources
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.