Spring MVC CSS file annotation configuration

By default, Spring Framework don't allow you request CSS file directly, you will get error like this

 
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVCAjaxExample/style.css] in DispatcherServlet with name 'dispatcher'
 

All the static files like CSS and javascript files called resources in Spring, and you need explicitly tell Spring where these resources are.

If you are using XML based configuration, and put all static files in resources folder in the application root, it goes like this

 
<mvc:resources mapping="/resources/**" location="/resources/" /> 
 

If you are using annotation based configuration, in your configuration class, extends WebMvcConfigurerAdapter and then add this method

 
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
 

You configuration file will looks like this

In you JSP file, reference css file like this

 
  <link href="resources/style.css" rel="stylesheet" type="text/css" />
 

See also