Search code examples
spring-bootthymeleaf

Spring-Boot doesn't load resource folder, using Thymeleaf


I've been trying to get this working but no luck after several hours.

My structure is like this:

🗁 src
└─── 🗁 main
    ├─── 🗁 java
    └─── 🗁 resources
        ├─── 🗁 META-INF
        │   └─── 🗁 resources
        │       └─── 🗁 bootstrap
        │           ├─── 🗁 css
        │           └─── 🗁 js
        ├─── 🗁 templates
        │   └─── index.html
        └─── application.properties

Here is the WebConfig class:

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
    }

}

If I use link to a web resource, it works:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>

If I'm trying to include a static resource, it doesn't work:

<link type="text/css" rel="stylesheet" href="../../../resources/bootstrap/css/bootstrap.min.css" 
    data-th-href="@{/resources/bootstrap/css/bootstrap.min.css}" />

Any help is highly appreciated.

Thank you


Solution

  • The issue has been solved. Unfortunately the problem wasn't from any of the above, it was from a controller mapped to "/". If you have the same problem I had, please make sure you don't have anything mapped to "/". Now all resources are accessible through the URL.

    My new structure is as follow:

    src
       main
           java
           resources
               static
                   bootstrap
                      css
                      js
           templates
               index.html
           application.properties
    

    Here is the WebConfig class:

    @Configuration
    @EnableWebMvc
    public class WebAppConfig extends WebMvcConfigurerAdapter {
    
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
        }
    
    }
    

    The link is being included in the HTML as:

    <link type="text/css" rel="stylesheet" href="../bootstrap/css/bootstrap.min.css" 
        data-th-href="@{/bootstrap/css/bootstrap.min.css}" />