kbo*_*kbo 6 java spring thymeleaf spring-boot
我想使用页面thymeleaf.但我对静态文件有一些问题.我研究了问题(1,2,3有类似的问题),但它并不能帮助我.
我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>
Run Code Online (Sandbox Code Playgroud)
test.js
function testFunction(test) {
console.log(test);
}
Run Code Online (Sandbox Code Playgroud)
配置类
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");
super.addResourceHandlers(registry);
}
}
Run Code Online (Sandbox Code Playgroud)
和问题,当我加载test.html文件没有加载javascript.
@GetMapping(value = "web/test")
public String getTestHtmlPage() {
return "test";
}
Run Code Online (Sandbox Code Playgroud)
/api/v1 是一个配置 application.properties => server.servlet-path=/api/v1
我做错了什么?你能帮助我吗?
谢谢大家!
为了更好地了解 registry.addResourceHandler("/**").addResourceLocations("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内容。
| 归档时间: |
|
| 查看次数: |
9689 次 |
| 最近记录: |