简体   繁体   中英

Fix location path to .css with Thymeleaf (Spring Boot)

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

Spring boot default BasicErrorController would directly look at src/main/resources/templates/ folder if you add your error html page there as "error.html" you can show that whenever error occurs

I faced the same issue when my URL had multiple "/". But I did not make any special changes except for changing my css links as follows.

<link rel="stylesheet" th:href="@{~/css/main.css}">

And same with javascript files as well.

On a side note, I don't use @EnableWebMvc annotation. It kinda messes up with automatic SpringMVC configuration.

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