首页 > 解决方案 > 使用 Thymeleaf (Spring Boot) 修复 .css 的位置路径

问题描述

我正在使用 Spring Boot 进行项目。我有一个 main.css 文件/src/main/resources/static/css/

我使用此 thymeleaf 代码将 .css 文件注入 /templates 文件夹中的 .html 文件:

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

我可以分别通过http://localhost:1126/css/main.css

我将此 .html 用作详细的错误页面。因此,如果 URL 不存在,请显示此 .html。如果 URL 具有“一个深度”(例如localhost:1126/something),它可以正常工作(显示 .html 并加载 .css)。
但是,如果我使用至少具有“两个深度”的 URL,或者甚至在末尾使用“/”(例如localhost:1126/something/localhost:1126/something/anything),它就不起作用(显示 .html 但未加载 .css)

问题是,在第二种情况下,Spring 尝试在下面找到 .css 文件localhost:1126/something/css/main.css

到目前为止我尝试过的事情:
使用th:href="@{/css/main.css}"而不是th:href="@{css/main.css}"

@SpringBootApplication
@EnableWebMvc
public class SpringBootProjectApplication implements WebMvcConfigurer {
    public static void main(String[] args) {
    SpringApplication.run(SpringBootProjectApplication.class, args);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
    }
}

我发现这些线程没有解决我的问题:

Thymeleaf、IntelliJ 和 Spring Boot 无法正确加载 CSS 文件
Spring Boot、Thymeleaf 和 CSS
CSS 文件无法定位 thymeleaf Spring Boot

标签: javacssspring-bootthymeleaf

解决方案


当我的 URL 有多个“/”时,我遇到了同样的问题。但我没有做任何特别的改变,除了改变我的css链接如下。

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

与 javascript 文件相同。

附带说明一下,我不使用 @EnableWebMvc 注释。它有点搞砸了自动 SpringMVC 配置。


推荐阅读