简体   繁体   中英

CSS file cannot be located thymeleaf Spring Boot

I'm setting up a Spring boot server and I just can't get Thymeleaf to link to the CSS. I know there are a number of similar questions but none of them lead me to an answer.

This is the link included in my "home.html".

<link rel="stylesheet" type="text/css"
      href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />

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

bootstrap.min.css links fine but main.css gives me a 404.

Project Structure

This is what it shows me in the web console under networks, this url takes me to a Whitelabel error

Request URL:http://localhost:8080/styles/main.css

Try creating a folder under resources called static and a subfolder called css and move your css files there, something like: resources/static/css/main.css

Then call it like:

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

By default there should be a static folder and your css content should be there or public all inside resources . Look at the springboot console when you run the app and look where it's serving resources from. Example below:

Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Based on the info above set your resource location accordingly.

Have you tried:

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

?

Your styles folder is located at the root of the classpath; it should be moved to a location that's actually configured by Spring Boot (see "serving static content" in the Spring Boot reference documentation ).

In your case, moving src/main/resources/styles to src/main/resources/static/styles should do the trick.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(
            "/img/**",
            "/css/**",
            "/libs/**")
            .addResourceLocations(
                    "classpath:/static/img/",
                    "classpath:/static/css/",
                    "classpath:/static/libs/");
    }

}

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