87

In my current spring-boot project, my views have this line:

<link href="signin.css" rel="stylesheet"/>

to reference a static css file. When I run the project, and access one of the views which reference this file, I get a 404 not found error or a 403 unauthorized error, depending where I put the file inside the project.

I try this so far:

src/main/resources/static/css (with this, I use css/signin.css instead of signin.css)

src/main/resources/templates/static/css (with this, I use css/signin.css instead of signin.css)

src/src/main/resources/templates/acesso (same folder of the html file)

what the right place to store this type of files?

nabster
  • 1,561
  • 2
  • 20
  • 32
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188

11 Answers11

128

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.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • 5
    bad luck for me, none of the posted solutions here on SO worked for me :/ – mfaisalhyder May 20 '16 at 21:43
  • 2
    Is there any configuration which needs to be done to make spring boot use src/main/resources/static as the default location? It's not picking up my css unless I load it from a CDN with a full url. – mojave May 07 '17 at 21:35
  • 7
    No, that's the default location. Just make sure you haven't used `@EnableWebMvc` in your application as that will disable Spring Boot's auto-configuration of Spring MVC. – Andy Wilkinson May 08 '17 at 13:24
  • Hi @AndyWilkinson, May I know how to handle the case when I have to use EnableWebMvc in my Spring Boot App. – Akash Goswami Sep 12 '17 at 18:47
  • Why would you have to use `@EnableWebMvc` rather than a `WebMvcConfigurerAdapter`? – Andy Wilkinson Sep 13 '17 at 09:28
  • Thank you. This answer worked perfectly for me. I had been looking for nearly an hour to figure this out! It would be really helpful to have a link or something showing where you found this information. – Kylon Tyner Mar 23 '18 at 21:48
  • Thanks for this, Andy. I spent over an hour trying out various suggestions as to where to put Javascript files - static, WEB-INF, etc.. My Spring Boot application wouldn't load them. But deleting @EnableWebMVC from a Controller ENABLED loading from these folders as a side effect. Who'd have thought? – rodmclaughlin Feb 17 '19 at 17:13
  • Removing @EnableWebMvc did the trick for me. I have been working on this one for hours! Wish I had seen this post earlier!! – Hua Feb 20 '19 at 00:25
  • It doesnt work for me... I have empty project with 1 controller with GetMapping("/") and 1 template in template dir and static/css/style.css. If i try to open it as with default browser - works. If i start Spring Boot and go to localhost:8080/ - html without styles. – andrew17 Dec 25 '19 at 23:36
  • Removing `@EnableWebMvc` helped me too, thanks! – 0xDEADBEEF Dec 08 '20 at 18:58
14

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>
jpllosa
  • 2,066
  • 1
  • 28
  • 30
12

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.

scorpion
  • 671
  • 1
  • 9
  • 16
7

I use Spring-Boot 2.0.2

I still keep @EnableWebMvc annotation in my webConfig.java and override addResourceHandlers() method to help browser reaches css and javascript files through http request.

This is the webapp directory's structure

directory structure.

webConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "example.com")
public class WebConfig implements WebMvcConfigurer {

    // =======================================
    // =             Bean Config             =
    // =======================================

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");

        return resolver;
    }


    // =======================================
    // =          Override Methods           =
    // =======================================

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pdfs/**")
                .addResourceLocations("/WEB-INF/pdfs/");

        registry.addResourceHandler("/css/**")
                .addResourceLocations("/WEB-INF/css/");

        registry.addResourceHandler("/js/**")
                .addResourceLocations("/WEB-INF/js/");
    }
}

index.jsp head tag:

<head>
    <title>Title</title>

    <!-- Custom styles for this template -->
    <link href="css/cover.css" rel="stylesheet">
</head>

hope it helps you.

ldt
  • 71
  • 2
  • 5
  • It might not help now. Question was asked in 2014. Try to answer recent question. Will help you and me both.... – MyTwoCents Jun 15 '18 at 13:50
  • 1
    @Ashish451 sorry if it is not the case, but if the answer is good and contributes, it isn't wrong answering old questions :). https://meta.stackexchange.com/questions/23996/does-it-make-sense-to-answer-old-questions – tk3 Jun 15 '18 at 16:17
  • Not working. try using this `registry.addResourceHandler("/WEB-INF/**").addResourceLocations("classpath:/WEB-INF/");` – hamza saber Dec 27 '19 at 12:07
6

Disabling @EnableWebMvc helped me to resolve issue.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
user2069692
  • 79
  • 1
  • 2
4

I use Spring-Boot with Thymeleaf http://www.thymeleaf.org/

This is the directory's structure like @Andy Wilkinson Response

enter image description here

Example

<link rel="stylesheet" href="../static/css/w3.css" th:href="@{/css/w3.css}">
Joao Ferreira
  • 395
  • 4
  • 9
2

I found that if I put my signin.css under src/main/resources/META-INF/resources/static/css/signin.css, then I could access it using /css/signin.css

Not sure why though.

rrudland
  • 410
  • 3
  • 8
2

In my case to reference files inside css and js folders like this:

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

I had to place the folders in webapp folder. I have the following folder structure:

Myapp

-src
     -main
           -java
           -resources
                    -static
                    -templates
           -webapp
                  -resources
                  -WEB-INF

I mean if i had placed the css and js folders in resources folder (under main) it would have been:

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

If i place them in static folder (under resources) it doesn't work.

Kike Lebowski
  • 501
  • 6
  • 6
  • I that really working? I can't let it work with names like bootstrap.min.css or bootstrap.min.js, while is working perfectly with names with no dots in basename, like somestyle.css or somescript.js. See https://stackoverflow.com/questions/47722325/spring-serving-static-contents-with-dots-in-filename – Marcoc1712 Dec 09 '17 at 18:43
1

When i used:

src/main/resources/static/css.

my views have this line:

<link rel="stylesheet" href="/css/signin.css" />
0
  • src/resource/static/css
  • src/resource/static/js
  • src/resource/static/images

Don't use @EnableWebMvc if you are using spring boot and check spring security.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
0

Put the required files inside static folder in spring boot. And then you can access the required files inside the jsp directly.

Hope it helps as it worked for me.

Yoshita Mahajan
  • 443
  • 4
  • 6