![](/img/trans.png)
[英]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.