java - 使用 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
解决方案
当我的 URL 有多个“/”时,我遇到了同样的问题。但我没有做任何特别的改变,除了改变我的css链接如下。
<link rel="stylesheet" th:href="@{~/css/main.css}">
与 javascript 文件相同。
附带说明一下,我不使用 @EnableWebMvc 注释。它有点搞砸了自动 SpringMVC 配置。
推荐阅读
- java - 如何隐藏方法内部的逻辑但使用proguard保留方法名称
- python - 在 PyCharm 中安装 GeoPy(在 MacOS 上)
- groovy - 捕获 Helm 包名称,一旦它形成
- html - Bootstrap 4折叠导航栏有2列
- css - 在材质组件中将组件特定样式设置为生成的 HTML
- php - 在laravel php中将现有图像转换为base64
- windows-runtime - 是否可以在我自己的运行时类上实现 Windows 类型的 [exclusiveto] 接口?
- json - Fusioncharts 线是舍入值
- excel - 在 VBA 中解析 Jscript ES3 中的 XMLHTTP responseText (HTML)
- gcc - 在另一台机器上为特定机器编译