【发布时间】:2017-07-26 22:21:42
【问题描述】:
我想使用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>
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);
}
}
问题是,当我加载 test.html 文件时未加载 javascript。
@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 错误。当我改成
<script src="test.js" th:href="@{/test.js}"/>时响应状态是200,但是在控制台出现一个新的错误Refused to execute script from 'http://localhost:8080/api/v1/web/test.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.是什么意思? -
我不知道 Thymeleaf,但查看 docs 表明
th:href适用于 HTML 内容。 Javascript 不是 HTML,所以你应该删除th:href并将src更改为th:src我猜。 -
@ChristopherSchneider,哦,是的,这是个愚蠢的错误,我改为
th:src,我现在收到404 错误,请求文件看起来像http://localhost:8080/api/v1/web/js/test.js。我没有这个端点。 -
和你原来的错误一样...
标签: java spring spring-boot thymeleaf