Html 在 spring mvc 中使用 thymeleaf 引用 .css 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25996056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:45:31  来源:igfitidea点击:

reference a .css file with thymeleaf in spring mvc

htmlcssspringspring-mvcthymeleaf

提问by stackUser2000

I am doing a project with spring MVC and Thymeleaf. I have a question about how I should reference my CSS files if I have this folder structure:

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

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

My configuration class is like this:

我的配置类是这样的:

@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/**");
}

And I call hrefin my index file like this:

href像这样调用我的索引文件:

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

But there are some elements that are kind of messed up in my page, for example the CSS is not working.

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

回答by Naresh Vavilala

You will need to use th:hrefattribute for referring css files. Here is a sample from thymeleaf tutorial. If thymeleaf can not evaluate th:hrefvalue, it defaults to hrefvalue.

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

<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>

回答by Максим Кмец

I have such problem!That steps helped me.

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

  1. I have the directory /resources/css/myCSS.css. So I had put css into root like /css/myCSS.css and removed directory /resources
  2. I link MyCSS like this:
  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" />

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