Junjie Junjie - 1 year ago 104
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.

│ └─com
│ └─ma2oo
│ └─quizbox
│ ├─application
│ ├─config
│ └─controllers
│ ├─css
│ └─js

The web config file is:

public class WebConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("reached here ");

public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download