简体   繁体   中英

reference a .css file with thymeleaf in spring mvc

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:

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="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.

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

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

<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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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