我尝试将我的应用程序从Spring Boot 1.5迁移到2.0。问题是我找不到EmbeddedServletContainerCustomizer。任何想法如何做到这一点?
@Bean public EmbeddedServletContainerCustomizer customizer() { return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated")); }
更新: 我在org.springframework.boot.autoconfigure.web.servlet包中找到它作为ServletWebServerFactoryCustomizer。
@Bean public ServletWebServerFactoryCustomizer customizer() { return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated")); }
但是有一个错误:无法解析方法
‘addErrorPages(org.springframework.boot.web.server.ErrorPage)’
我还必须将新错误页面的导入从更改org.springframework.boot.web.servlet为org.springframework.boot.web.server
org.springframework.boot.web.servlet
org.springframework.boot.web.server
从Spring Boot 2开始, WebServerFactoryCustomizer 取代了 EmbeddedServletContainerCustomizer :
@Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() { return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html")); }
或者, 您可以添加一个视图控制器,例如
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/unauthorized").setViewName("forward:/401.html"); }
然后您的WebServerFactory应该指向/ unauthorized:
@Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() { return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthorized")); }