gpt4 book ai didi

javascript - 将 js 从文件系统加载到 spring boot jar 应用程序中(使用 thymeleaf)

转载 作者:行者123 更新时间:2023-11-30 16:02:10 25 4
gpt4 key购买 nike

我有一种使用 spring boot 制作的实用程序,将捆绑的 tomcat 打包到可执行 jar 中。我需要的是将一些 js(或可能是 json)文件放在与 jar 文件相同的文件夹中,并能够将它们插入到 thymeleaf 模板中。例如

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

到目前为止,我已经设法做到了:在 Controller 中:

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

在模板中:

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

此时我可以通过 firebug html View 看到 myfile.js 中的代码,但在脚本选项卡中看不到,也没有执行脚本(此文件中定义的任何变量都是未定义的)。

怎么做?

我知道我可以创建一个 json 文件并通过 java 处理它,但是如果我正在搜索的解决方案存在,它对我来说使用起来更简单、更方便,而且这样我可以使用自定义 js,而不仅仅是 json。

我也知道这在很多情况下是非常不安全的,但在这种情况下,应用程序根本不需要安全,无论人们想通过文件注入(inject)什么。

最佳答案

您可以自定义 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 Common Properties Appendix

你需要在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

关于javascript - 将 js 从文件系统加载到 spring boot jar 应用程序中(使用 thymeleaf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37563578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com