在spring mvc中引用一个带有百里香的.css文件

sta*_*000 6 html css spring spring-mvc thymeleaf

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

src
  main
    webapp
     resources
       myCssFolder
         myCssFile.css
     web-inf
       spring
       views
         myViewFolder
           index.html
Run Code Online (Sandbox Code Playgroud)

我的配置类是这样的:

@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/**");
}
Run Code Online (Sandbox Code Playgroud)

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

href="resources/css/bootstrap.min.css"
Run Code Online (Sandbox Code Playgroud)

但是有一些元素在我的页面中搞砸了,例如CSS无效.

Nar*_*ala 10

您将需要使用th:href属性来引用css文件.以下是百里叶教程的示例.如果百里香叶无法评估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>
Run Code Online (Sandbox Code Playgroud)

  • 您的配置似乎是正确的。但是,你应该在`webapp/css/` 文件夹中有你的css 文件,你应该使用`th:href="@{/css/bootstrap.min.css}"` 来引用它 (2认同)

小智 5

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

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

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


Afs*_*Ali 5

我在下面使用并且工作正常 在此输入图像描述

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

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