【问题标题】:springboot thymeleaf could not find static filesspringboot thymeleaf 找不到静态文件
【发布时间】:2016-11-28 09:06:59
【问题描述】:

我用springboot + thymeleaf,可以找到模板页面,但是找不到静态的(css或js)。

application.yml:

spring:
  application:
    name: exe-springboot
  thymeleaf:
    suffix: .html
  resources:
    static-locations: /static/**

和控制器:

@RequestMapping("/index")
public String index() {
    return "index";
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>index</title>
    <link rel="stylesheet" href="../static/index.css"/>
</head>
<body>
<h2>test page</h2>
<span class="test-span">hello world with css</span>
</body>
</html>

index.css

.test-span{
    font-size: 20px;
    color: red;
}

和浏览器:http://localhost:8080/index hello world with css 的例外颜色应该是红色,但不是。和带有 chrome 的控制台显示 404 http://localhost:8080/static/index.css

【问题讨论】:

  • 您可以在index.html 页面中尝试&lt;link rel="stylesheet" th:href="@{/static/index.css}" /&gt; 吗?
  • 我用&lt;link rel="stylesheet" th:href="@{index.css}"/&gt;做的,不行,用&lt;link rel="stylesheet" th:href="@{../static/index.css}"/&gt;做的,还是不行,控制台显示404http://localhost:8080/static/index.css第二种方式。
  • 只是localhost:8080/index.css。不要添加“静态”它也会给出 404 吗?
  • 不是 404,但还是不行
  • 当您在浏览器中查看页面的源代码并单击 时,如果您获取带有文件 index.css ('.test-span{ font-size: 20px; color: red; }' )源的页面,然后加载它并且问题出在其他地方?如果您有安全性,可能会或其他什么?

标签: spring-boot thymeleaf


【解决方案1】:

尝试像这样访问静态目录中的资源:

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

当您使用 thymeleaf 时,请不要忘记“th:”,您也不必将整个路径写入您想要的资源。 Spring 正在查看静态目录,因此您可以像在我的示例中一样访问 index.css。

另外一个好的做法可能是将您的 css、js、字体和图像放入静态目录中的不同文件夹中。例如,创建一个文件夹 CSS 并将 index.css 放入其中并在您的 HTML 中访问它,例如:

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

编辑:

现在问题不在于从静态文件夹加载资源。如您所见,您收到状态代码 200,这意味着 index.css 已加载到您的 HTML。

所以我可以建议您最好将标签替换为:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">

【讨论】:

  • 我做到了&lt;link rel="stylesheet" th:href="@{index.css}"/&gt;,还是不行。
  • 你可以试试像:&lt;link rel="stylesheet" th:href="@{/index.css}"/&gt; 和'/'。同样在您的浏览器中输入:localhost:8080/index.css 并且也会给您 404 吗?
  • &lt;link rel="stylesheet" th:href="@{/index.css}"/&gt;没有404,但是还是不行,看我的ans如下
猜你喜欢
  • 2016-06-18
  • 2018-09-21
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 2014-11-10
  • 2011-08-26
  • 2020-06-22
相关资源
最近更新 更多