【问题标题】:Spring Boot, Thymeleaf and CSSSpring Boot、Thymeleaf 和 CSS
【发布时间】:2020-08-16 14:07:30
【问题描述】:

这真的很愚蠢,但我无法让它工作。

在我的 spring boot mvc 应用程序中,假设有 5 个百里香叶模板,其中一个是 error.html。

当请求任何无效路由时,error.html 会派上用场。

当无效路由嵌套(如 2 级或更多级别)然后 css 不适用时,会发生此问题。

例如:

http://localhost:3000/application/index- valid route and css is applied
http://localhost:3000/application/success- valid route and css is applied
http://localhost:3000/application/failure- valid route and css is applied
http://localhost:3000/application/invalidroute- route does not exist but css is applied
http://localhost:3000/application/invalidroute/something - route does not exist and css is also not applied

我的 CSS 位于 static 文件夹下的 css 文件夹中

所有 thymeleaf 模板都在同一级别,并通过访问 css

 <link rel="stylesheet" href="css/main.css"/>

控制台出现错误

GET http://localhost:3000/application/invalidroute/css/main.css net::ERR_ABORTED 404

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    代替

    <link rel="stylesheet" href="css/main.css"/>
    

    使用这个:

    <link rel="stylesheet" th:href="@{/css/main.css}" />
    

    并确保这是您的文件占位符

    src/main/resource/static/css - 用于 CSS 文件

    src/main/resource/templates - 用于 HTML 模板文件

    【讨论】: