[英]Load static resource in Spring Boot with Thymeleaf
I want to make page using thymeleaf
. 我想用
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.
我调查过的问题( 1 , 2 , 3有类似的问题),但它并没有帮助我。
I use Spring Boot
framework in the application. 我在应用程序中使用
Spring Boot
框架。 My files look like: 我的文件看起来像:
test.html 的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 test.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. 和问题,当我加载没有加载javascript的
test.html
文件。
@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! 谢谢大家!
For a better understanding of registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
为了更好地理解
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
I wrote a more thorough answer here that 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/
的方式classpath:/static/js/
,然后访问/js/test.js
,你告诉Spring查看/static/js/js/test.js
。
What you probably want is classpath:/static/
. 你可能想要的是
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. 在这种情况下,当您尝试访问
/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
. 至于Thymeleaf,我从来没有使用它,但文档表明你应该用
th:src
而不是th:href
加载脚本。 th:href
appears to only be for HTML content. th:href
似乎只适用于HTML内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.