Where to put static files such as CSS in a spring-boot project?

Solution 1:

Anywhere beneath src/main/resources/static is an appropriate place for static content such as CSS, JavaScript, and images. The static directory is served from /. For example, src/main/resources/static/signin.css will be served from /signin.css whereas src/main/resources/static/css/signin.css will be served from /css/signin.css.

The src/main/resources/templates folder is intended for view templates that will be turned into HTML by a templating engine such as Thymeleaf, Freemarker, or Velocity, etc. You shouldn't place static content in this directory.

Also make sure you haven't used @EnableWebMvc in your application as that will disable Spring Boot's auto-configuration of Spring MVC.

Solution 2:

Apart from placing it anywhere beneath src/main/resources/static and not using @EnableWebMvc, you'll need to authorize access to your js or css folder especially if you have spring-boot-security in you classpath. You'll add something like this:

@Configuration
@EnableWebSecurity
public class MainSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home", "/js/**", "/css/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

Then in your HTML:

<link rel="stylesheet"  href="/css/bootstrap.min.css">
<script src="/js/bootstrap.min.js"></script>

Solution 3:

You can use Thymeleaf http://www.thymeleaf.org/

Example

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" th:href="@{/css/signin.css}"/>
</head>
<body>
</body>
</html>

Remember to add xmlns and xmlns:th in your html tag.

Check your application.properties:

spring.resources.add-mappings=true

If that key is set to false, spring boot app will not load any resources.

Solution 4:

Disabling @EnableWebMvc helped me to resolve issue.