问题
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
回答1:
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.
回答2:
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}"/>
回答3:
Have you tried:
<link rel="stylesheet" type="text/css" th:href="@{../styles/main.css}" />
?
回答4:
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.
回答5:
@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/");
}
}
来源:https://stackoverflow.com/questions/46318008/css-file-cannot-be-located-thymeleaf-spring-boot