Javascript 将js从文件系统加载到spring启动jar应用程序中(使用thymeleaf)

Javascript 将js从文件系统加载到spring启动jar应用程序中(使用thymeleaf),javascript,java,json,spring,Javascript,Java,Json,Spring,我有一种用SpringBoot制作的实用程序,它将捆绑的tomcat打包到可执行的jar中。 我需要的是将一些js(或者可能是json)文件放在与jar文件相同的文件夹中,并能够将它们插入到thymeleaf模板中。 e、 g 在模板中: <script type="text/javascript" th:src="${userDir + 'myfile.js'}"></script> 此时,我可以通过firebug html视图看到myfile.js中的代码,但不

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

在模板中:

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

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

怎么做

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


我也知道这在很多情况下是非常不安全的,但在这种情况下,应用程序根本不必是安全的,不管您想通过文件注入什么。

您可以自定义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您的_-jar_文件--resources=/path/to/resources/

还请注意,此路径中的资源是根据/myresources/路径注册的,因此您需要按如下所示修改模板

<script type="text/javascript" src="myresources/myfile.js"></script>
将您的位置附加到它。您也可以像这样使用文件资源

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

明亮的非常感谢。
<script type="text/javascript" src="myresources/myfile.js"></script>
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