Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 794
stackUser2000 Avatar asked Sep 23 '14 13:09

stackUser2000


People also ask

How do I link a CSS file to Thymeleaf?

Adding CSS. We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main.

Is Thymeleaf supported by Spring MVC?

Thymeleaf offers a set of Spring integrations that allow you to use it as a fully-featured substitute for JSP in Spring MVC applications.


2 Answers

I used below and worked ok enter image description here

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}" />

like image 131
Afsar Ali Avatar answered Sep 28 '22 08:09

Afsar Ali


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>
like image 32
Naresh Vavilala Avatar answered Sep 28 '22 08:09

Naresh Vavilala