【问题标题】:Fix location path to .css with Thymeleaf (Spring Boot)使用 Thymeleaf (Spring Boot) 修复 .css 的位置路径
【发布时间】:2020-10-10 15:34:44
【问题描述】:

我正在使用 Spring Boot 开发一个项目。我在/src/main/resources/static/css/ 下有一个 main.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尝试在localhost:1126/something/css/main.css下找到.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 and Spring Boot not loading CSS files correctly
Spring Boot, Thymeleaf and CSS
CSS file cannot be located thymeleaf Spring Boot

【问题讨论】:

    标签: java css spring-boot thymeleaf


    【解决方案1】:

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

    &lt;link rel="stylesheet" th:href="@{~/css/main.css}"&gt;

    javascript 文件也是如此。

    附带说明,我不使用@EnableWebMvc 注释。它与自动 SpringMVC 配置有点混乱。

    【讨论】:

      【解决方案2】:

      Spring boot 默认 BasicErrorController 将直接查看 src/main/resources/templates/ 文件夹,如果您将错误 html 页面添加为“error.html”,您可以在发生错误时显示

      【讨论】:

      • html 显示正确,我的问题是,如果 URL 有多个来自根的“标签”(如 localhost:port/onetag/anothertag),则不会加载 css 文件。
      • 如果没有任何请求映射可以用一个斜杠或其他方式处理您的 uri,那将是一个错误,我想我无法理解您
      • 这是一个错误完全可以。问题:如果 URL 包含至少两个“/”(一个在端口号之后,一个在任何位置),为什么 css 文件不与 html 一起加载?
      猜你喜欢
      • 2017-05-26
      • 2020-11-11
      • 2020-08-16
      • 2020-12-12
      • 2015-06-11
      • 2017-07-30
      • 2017-06-28
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多