这真的很傻,但我无法让它工作。
在我的 spring boot mvc 应用程序中,假设有 5 个 thymeleaf 模板,其中一个是 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
最佳答案
代替
<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 模板文件
关于spring-boot - Spring Boot、Thymeleaf 和 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61553420/