3

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?

Martin
  • 1,265
  • 2
  • 17
  • 48

1 Answers1

8

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.

Andy Wilkinson
  • 85,432
  • 19
  • 215
  • 204
  • Thank you Andy, thought I read all the relevant stuff in there yesterday night but I guess it was late. This does indeed fix it but is there a way for this to be done programmatically somehow? Trying to cut down on the number of properties in my application.properties file. Thanks! – Martin Nov 13 '20 at 14:29
  • 1
    There's a setter on `TomcatServletWebServerFactory` that you can use. I've updated my answer. – Andy Wilkinson Nov 13 '20 at 15:37
  • The programmatic method doesn't work, I can only get past this error with the property – Martin Nov 13 '20 at 15:43
  • 1
    Ah, yes. That's an ordering problem that causes the configuration to be overridden. I've updated the answer with a better approach. – Andy Wilkinson Nov 13 '20 at 18:02
  • Yep that worked! Thanks Andy, you guys are awesome! Thanks for a great product! – Martin Nov 16 '20 at 14:05