我想使用thymeleaf
制作页面。但是我有一些静态文件的问题。我正在调查问题(1,2,3),但它对我没有帮助。用Thymeleaf加载Spring Boot中的静态资源
我在应用程序中使用了一个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/v1
是application.properties => server.servlet-path=/api/v1
我做的不对的配置?你可以帮我吗?
谢谢大家!
您没有包含test.js的错误...是404吗?实际路径应该是'test.js'而不是'js/test.js' –
是的,它是404错误。当我更改为'时,响应状态为200,但在控制台中出现一个新错误“拒绝执行脚本” :// localhost:8080/api/v1/web/test.js',因为它的MIME类型('text/html')不可执行,并且启用严格的MIME类型检查。“这是什么意思? –
我不知道Thymeleaf,但看[docs](http://www.thymeleaf.org/doc/articles/standardurlsyntax.html)指出'th:href'适用于HTML内容。 Javascript不是HTML,所以你应该删除'th:href'并将'src'改为'th:src'。 –