【问题标题】:Load static resource in Spring Boot with Thymeleaf使用 Thymeleaf 在 Spring Boot 中加载静态资源
【发布时间】: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/v1application.properties =&gt; server.servlet-path=/api/v1中的一个配置

我做错了什么?你能帮帮我吗?

谢谢大家!

【问题讨论】:

  • 您没有包含 test.js 的错误...是 404 吗?实际路径应该只是 test.js 而不是 js/test.js
  • 是的,这是 404 错误。当我改成&lt;script src="test.js" th:href="@{/test.js}"/&gt;时响应状态是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


【解决方案1】:

为了更好地理解registry.addResourceHandler("/**").addResourceLocations("classpath:/static/js/");

我写了一个更详尽的answer here,讨论了无效的资源位置映射。它没有收到任何赞成票,所以我希望它不可怕。 :-)

简而言之,通过映射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 内容。

【讨论】:

  • 感谢您的回答,我尝试根据您的回答进行更改。我在源代码中发现了问题。我在application.properties 中使用属性server.servlet-pathserver.servlet-path 是控制器的平均路径,等于 /api/v1。我什么时候在没有server.servlet-path 属性的情况下提出请求一切正常(网址http://localhost:8080/css/main.css)。如果使用 server.servlet-path 属性请求,那么我将收到 404 错误(url 与 server.servlet-path 属性相同,但 我认为它必须更改)。也许你知道?我找不到解决方案..
  • 我被添加到 api/v1th:hrefth:src它工作。我可以用其他方式吗?当server.servlet-path 将被更改时,我还必须更改所有.html 文件中的路径:-(
  • 我不太确定,因为我没有使用 Thymeleaf 的经验。我建议查看文档以了解 th:hrefth:src 如何解析路径。似乎他们不知道 servlet-path。可能有一个设置,因此 Thymeleaf 知道您可以设置的上下文根。
最近更新 更多