IllegalStateException after upgrading web app to Spring Boot 2.4
Asked Answered
A

1

18

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?

Acropetal answered 13/11, 2020 at 14:0 Comment(0)
L
40

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.

Lateritious answered 13/11, 2020 at 14:17 Comment(5)
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!Acropetal
There's a setter on TomcatServletWebServerFactory that you can use. I've updated my answer.Lateritious
The programmatic method doesn't work, I can only get past this error with the propertyAcropetal
Ah, yes. That's an ordering problem that causes the configuration to be overridden. I've updated the answer with a better approach.Lateritious
Yep that worked! Thanks Andy, you guys are awesome! Thanks for a great product!Acropetal

© 2022 - 2024 — McMap. All rights reserved.