繁体   English   中英

使用Thymeleaf在Spring Boot中加载静态资源

[英]Load static resource in Spring Boot with Thymeleaf

我想用thymeleaf来制作页面。 但我对静态文件有一些问题。 我调查过的问题( 123有类似的问题),但它并没有帮助我。

我在应用程序中使用Spring Boot框架。 我的文件看起来像: 在此输入图像描述

的test.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script src="js/test.js" th:src="@{/test.js}"/>
</head>
<body>
<button onclick="testFunction('test value')">Button</button>
</body>
</html>

test.js

function testFunction(test) {
    console.log(test);
}

配置类

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
        super.addResourceHandlers(registry);
    }
}

和问题,当我加载没有加载javascript的test.html文件。

@GetMapping(value = "web/test")
public String getTestHtmlPage() {
    return "test";
}

在此输入图像描述

/api/v1application.properties => server.servlet-path=/api/v1

我做错了什么? 你能帮助我吗?

谢谢大家!

为了更好地理解registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");

在这里写了一个更全面的答案 ,讨论了无效的资源位置映射。 它没有收到任何赞成票,所以我希望它并不可怕。 :-)

简而言之,通过映射classpath:/static/js/的方式classpath:/static/js/ ,然后访问/js/test.js ,你告诉Spring查看/static/js/js/test.js

你可能想要的是classpath:/static/ 在这种情况下,当您尝试访问/js/test.js ,它会在/static/js/test.js查找该文件。

至于Thymeleaf,我从来没有使用它,但文档表明你应该用th:src而不是th:href加载脚本。 th:href似乎只适用于HTML内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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