Junjie Junjie - 2 months ago 6
CSS Question

css file can't be loaded with spring boot

following is my file dir tree, and html files is in src/main/webapp/templates, have added src/main/webapp into classpath.

src──main
├─java
│ └─com
│ └─ma2oo
│ └─quizbox
│ ├─application
│ ├─config
│ └─controllers
├─resources
└─webapp
├─static
│ ├─css
│ └─js
└─templates


The web config file is:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("reached here ");
registry.addResourceHandler("/resources/**").addResourceLocations("/static/");
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
}


And the ref link in html is:

<link href="/static/css/components.css" rel="stylesheet"></link>


When web server is running, I can't get the expected result from browser, it's just same with there is no css existed.

Could anyone help with it please?
Thanks in advance.

Answer

Since you are using Spring Boot, it is not the best idea to have the resources in under webapp. See this part of this official Spring Boot documentation

I propose you move all the static content you now have under /webapp to /resources and also get rid of the addResourceHandlers configuration method since Spring boot will automatically map the static content correctly.

Then for example you would have <link href="css/components.css" rel="stylesheet"></link>

For a sample spring boot project that uses static content, check out this.