EmbeddedServletContainerCustomizer in spring boot 2.0
You don't need the container customizer to register your error pages. Simple bean definition implemented as a lambda does the trick:
@Bean
public ErrorPageRegistrar errorPageRegistrar() {
return registry -> {
registry.addErrorPages(
new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"),
);
};
}
From Spring Boot 2 on the WebServerFactoryCustomizer has replaced the EmbeddedServletContainerCustomizer:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"));
}
Alternatively you might add a view controller like
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/unauthorized").setViewName("forward:/401.html");
}
and then your WebServerFactory should point to /unauthorized instead:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthorized"));
}
I think you need ConfigurableServletWebServerFactory
, instead of ServletWebServerFactoryCustomizer
.
You can find the code snippet below:
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ServerConfig {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
return factory;
}
}
The above code is for Undertow. For tomcat, you need to replace UndertowServletWebServerFactory
with TomcatServletWebServerFactory
.
You will need to add the following dependency to your project (in case of Maven):
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-servlet</artifactId>
<version>2.0.26.Final</version>
</dependency>