【问题标题】:reference a .css file with thymeleaf in spring mvc在 spring mvc 中使用 thymeleaf 引用 .css 文件
【发布时间】:2014-11-17 17:11:33
【问题描述】:

我正在用 spring MVC 和 Thymeleaf 做一个项目。如果我有这个文件夹结构,我有一个关于如何引用我的 CSS 文件的问题:

src
  main
    webapp
     resources
       myCssFolder
         myCssFile.css
     web-inf
       spring
       views
         myViewFolder
           index.html

我的配置类是这样的:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/css/**").addResourceLocations("/css/**");
    registry.addResourceHandler("/img/**").addResourceLocations("/img/**");
    registry.addResourceHandler("/js/**").addResourceLocations("/js/**");
    registry.addResourceHandler("/sound/**").addResourceLocations("/sound/**");
    registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/**");
}

我在我的索引文件中调用href,如下所示:

href="resources/css/bootstrap.min.css"

但是我的页面中有些元素有点混乱,例如 CSS 不起作用。

【问题讨论】:

  • 如果您能展示您的项目结构以及向您的服务器发出资源的实际 HTTP 请求会很好
  • 找到解决方案了吗?

标签: html css spring spring-mvc thymeleaf


【解决方案1】:

您需要使用th:href 属性来引用css 文件。这是来自 thymeleaf 教程的示例。如果 thymeleaf 无法评估 th:href 值,则默认为 href 值。

<head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all"  
      href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
 </head>

【讨论】:

  • 不,@Narresh 向您展示的是如何使用 th:href 的示例
  • 您的配置似乎是正确的。但是,您应该将 css 文件放在 webapp/css/ 文件夹中,并且应该使用 th:href="@{/css/bootstrap.min.css}" 来引用它
【解决方案2】:

我有这样的问题!这些步骤帮助了我。

  1. 我有目录 /resources/css/myCSS.css。所以我把css像/css/myCSS.css一样放入根目录并删除目录/resources
  2. 我这样链接 MyCSS:

&lt;link th:href="@{/css/MyCSS.css}" href="/css/MyCSS.css" rel="stylesheet" type="text/css" /&gt;

【讨论】:

    【解决方案3】:

    我在下面使用并且工作正常

    这里我从css文件夹路径中使用..不包括静态文件夹

    &lt;link rel="stylesheet" type="text/css" media="all" href="/css/index.css" th:href="@{/css/index.css}" /&gt;

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2016-12-25
      • 2016-02-16
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      相关资源
      最近更新 更多