Junjie
Junjie

Reputation: 1175

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.

Upvotes: 1

Views: 10519

Answers (3)

paulos
paulos

Reputation: 32

If you have annotated your controller class, or one of your methods in your controller class, with @RequestMapping("/") remove the annotation and try it.

Upvotes: 1

geoand
geoand

Reputation: 63991

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.

Upvotes: 4

user486734
user486734

Reputation:

The URL you're using to reference the CSS file does not match the path pattern you registered in your resource handler. You need to use a link such as the following instead:

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

(Note that by default Spring Boot registers a handler for resources in the webapp root. However, by using the @EnableWebMvc annotation, you are overriding that default behavior. If you remove that annotation, then your existing HTML link would work as is.)

Upvotes: 0

Related Questions