Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 991
Raducu Avatar asked Jan 01 '26 18:01

Raducu


1 Answers

Avoid webapp folder with spring boot

  • Spring Boot documentation says:

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.

Where to place static files then?

  • Spring Boot serves static files in these folders (relative to /src/main/resources/):

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources).

I suggest you reorganize your webapp files into /src/main/resources/static

Other answers

  • spring-boot-configure-it-to-find-the-webapp-folder
  • spring-boot-cannot-find-index-html-under-webapp-folder

EDIT AFTER COMMENTS - Path to the static files

When accessing static files, the static folders (listed above) are the path's root.

Thus, to access your css file:

  • file in project: META-INF/resources/bootstrap/css/bootstrap.min.css
  • url: http://localhost:8080/bootstrap/css/bootstrap.min.css
  • link tag: <link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.min.css"/>
  • link tag: <link type="text/css" rel="stylesheet" data-th-href="@{bootstrap/css/bootstrap.min.css}" />
like image 130
alexbt Avatar answered Jan 04 '26 12:01

alexbt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!