javaspring-boottomcatservletscontextpath

IllegalStateException after upgrading web app to Spring Boot 2.4


My web app is no longer starting after upgrading to Spring Boot 2.4. It is throwing the following error :

Unable to locate the default servlet for serving static content. Please set the 'defaultServletName' property explicitly.

I am using the following code to change the context path and my research points me to that being the "culprit" (changing context path) :

@Bean
public ServletWebServerFactory servletContainer() 
{
    String tomcatPort = environment.getProperty("tomcatPort");
    
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.setPort(tomcatPort != null ? Integer.parseInt(tomcatPort) : 8080);
    tomcat.setContextPath("/Carbon");
    tomcat.setBaseDirectory(new File(System.getenv("MDHIS3_HOME")));
    
    setTomcatProtocol(tomcat);
    
    return tomcat;
}

I have the following method and I can see that it can be used to pass a defaultServletName but I have no idea what value I'm supposed to pass :

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) 
{
    configurer.enable();
}

This worked perfectly on Spring Boot 2.3.4. What value do I pass in there? Is it the name of the main controller?


Solution

  • As described in the Spring Boot 2.4 release notes, the DefaultServlet provided by the embedded Servlet container is no longer registered by default. If your application needs it, as yours appears to do, you can enable it by setting server.servlet.register-default-servlet to true.

    Alternatively, you can configure it programatically using a WebServerFactoryCustomizer bean:

    @Bean
    WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() {
        return (factory) -> factory.setRegisterDefaultServlet(true);
    }
    

    Note that the configuration must be applied via a customizer so that the default properties-based configuration does not overwrite it.