【发布时间】: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