I'm working on a project with Spring Boot. I have a main.css file under /src/main/resources/static/css/
I use this thymeleaf code to inject the .css file into a .html file from the /templates folder:
<link rel="stylesheet" th:href="@{/css/main.css}" href="../static/css/main.css" />
I can open it respectively via http://localhost:1126/css/main.css
I use this .html as a detailed error page. So if an URL doesn't exists, show this .html. If the URL is with "one depth" (for example localhost:1126/something) it works fine (.html is shown and .css is loaded).
But if I use URLs with at least "two depths", or even with an "/" at the end (for example localhost:1126/something/ or localhost:1126/something/anything) it doesn't work (.html is shown but .css IS NOT loaded).
The problem is that in the second case Spring try to find the .css file under localhost:1126/something/css/main.css
Things I've tried so far:
use th:href="@{/css/main.css}" instead of th:href="@{css/main.css}"
AND
@SpringBootApplication
@EnableWebMvc
public class SpringBootProjectApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
}
}
I have found these threads with no answers for my problem:
Thymeleaf, IntelliJ and Spring Boot not loading CSS files correctly
Spring Boot, Thymeleaf and CSS
CSS file cannot be located thymeleaf Spring Boot