25

By default, Spring Boot looks in my src/main/webapp folder to find my html files. Where can I change the settings for Spring Boot if I use another folder to put the html files?

Later, the files will be wrapped in jars for deployment. Are there other things I need to worry about?

user2191332
  • 1,059
  • 3
  • 17
  • 24

2 Answers2

27

See the docs: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

The static resources are loaded from /static, /public, /resources, /META-INF/resources

If you are packaging your application as a JAR (deploying a .jar), using src/main/webapp is not recommended.

You can customize that by overriding the addResourceHandlers method in WebMvcConfigurerAdapter

    @Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry){
             registry.addResourceHandler("/**")
                .addResourceLocations("/")
                .setCachePeriod(0);
        }
    }
Edwin Diaz
  • 1,693
  • 1
  • 12
  • 16
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • 30
    I think stating "Using `src/main/webapp` is not recommended" can be misinterpreted by the reader. According to the documentation "Do not use the src/main/webapp directory *if your application will be packaged as a jar*", so you should mention that as well. – Maksim Sorokin Jul 03 '15 at 14:03
  • 2
    Yes, that line is completely misleading. – takendarkk May 17 '17 at 17:01
  • 4
    Why spring boot does not work with `src/main/webapp` in jar packing? I was curious because what if we needed to migrate our existing `war` packaged app to Spring boot? – Akash Nov 13 '17 at 11:00
  • @akash Totally agree, this is what I am trying to do now for my project. – Ben Jan 31 '18 at 08:01
  • 1
    on Spring Boot `2.4.x` the default servlet is now disabled, which impacts on loading of these resources. You need `server.servlet.register-default-servlet=true` (or equivalent) in `application.properties`. – Nigel Sheridan-Smith Feb 09 '21 at 10:09
  • I use spring-boot version 2.3.7 and this solution didn't solve the problem. – Georgios Syngouroglou May 02 '21 at 22:49
12

AS mentioned above, jar packaging ignores webapp content. If you still want to include the contents inside webapp folder, you need to specify this explicitly in maven POM.xml configuration as below -

<build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources> ...
Akash
  • 4,412
  • 4
  • 30
  • 48