简体   繁体   English

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

[英]reference a .css file with thymeleaf in spring mvc

I am doing a project with spring MVC and Thymeleaf.我正在用 spring MVC 和 Thymeleaf 做一个项目。 I have a question about how I should reference my CSS files if I have this folder structure:如果我有这个文件夹结构,我有一个关于我应该如何引用我的 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 href in 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 不起作用。

You will need to use th:href attribute for referring css files.您将需要使用th:href属性来引用 css 文件。 Here is a sample from thymeleaf tutorial.这是 thymeleaf 教程中的示例。 If thymeleaf can not evaluate th:href value, it defaults to href value.如果 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>

I have such problem!That steps helped me.我有这样的问题!这些步骤帮助了我。

  1. I have the directory /resources/css/myCSS.css.我有目录/resources/css/myCSS.css。 So I had put css into root like /css/myCSS.css and removed directory /resources所以我把 css 像 /css/myCSS.css 一样放入根目录并删除目录 /resources
  2. I link MyCSS like this:我像这样链接 MyCSS:

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

I used below and worked ok我在下面使用并且工作正常在此处输入图片说明

here i used from css folder path .. not included static folder这里我从 css 文件夹路径中使用 .. 不包括静态文件夹

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM