java 使用 Thymeleaf 在 Spring Boot 中加载静态资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42635940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load static resource in Spring Boot with Thymeleaf
提问by boden
I want to make page using thymeleaf
. But I have some problem with the static files. I've investigated questions(1,2,3) with similar problem, but it didn't help me.
我想使用thymeleaf
.但是我对静态文件有一些问题。我调查过的问题(1,2,3有类似的问题),但它并没有帮助我。
I use Spring Boot
framework in the application.
My files look like:
我Spring Boot
在应用程序中使用框架。我的文件看起来像:
test.html
测试.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
测试.js
function testFunction(test) {
console.log(test);
}
Configuration class
配置类
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
super.addResourceHandlers(registry);
}
}
And problem, when I load test.html
file with javascript not loaded.
问题是,当我加载test.html
未加载 javascript 的文件时。
@GetMapping(value = "web/test")
public String getTestHtmlPage() {
return "test";
}
/api/v1
is a configuration in application.properties => server.servlet-path=/api/v1
/api/v1
是一个配置application.properties => server.servlet-path=/api/v1
What do I do wrong? Can you help me?
我做错了什么?你能帮助我吗?
Thanks all!
谢谢大家!
回答by Christopher Schneider
For a better understanding of registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
为了更好地了解registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
I wrote a more thorough answer herethat discusses invalid resource location mappings. It didn't receive any upvotes, so I hope it's not terrible. :-)
我在这里写了一个更彻底的答案,讨论无效的资源位置映射。它没有收到任何赞成票,所以我希望它不会太糟糕。 :-)
In short, with the way you're mapping classpath:/static/js/
, and then accessing, /js/test.js
, you're telling Spring to look in /static/js/js/test.js
.
简而言之,通过您映射classpath:/static/js/
和访问的方式/js/test.js
,您是在告诉 Spring 查找/static/js/js/test.js
.
What you probably want is classpath:/static/
. In that case, when you try to access /js/test.js
, it's looking in /static/js/test.js
for the file instead.
你可能想要的是classpath:/static/
. 在这种情况下,当您尝试访问 时/js/test.js
,它会/static/js/test.js
改为查找 文件。
As for Thymeleaf, I've never used it, but docs indicate you should load scripts with th:src
instead of th:href
. th:href
appears to only be for HTML content.
至于Thymeleaf,我从来没有使用过它,但文件表明您应该加载脚本th:src
代替th:href
。th:href
似乎仅适用于 HTML 内容。