天天看點

Spring Boot自定義Http Status錯誤頁面

在做spring boot項目的過程中,老是出現出錯界面,一律跳到spring boot預設的錯誤顯示界面,極大的影響使用者體驗,于是開始在網上尋找相關的解決辦法,出現最多的是使用EmbeddedServletContainerCustomizer類進行相關的頁面定義,但是在使用過程中,卻被告知該類已被删除,也沒告訴我用什麼替換。

後來在網上搜到一個問答上解決了這個問題,在此記錄一下,用ConfigurableServletWebServerFactory替換EmbeddedServletContainerCustomizer,具體代碼如下:

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
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 ServerConfiger {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND , "/login-error"));
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN , "/login-forbidden"));
        factory.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/method-not-allowed"));
        factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/method-not-allowed"));
        return factory;
    }
}
           

通過相應的Http status來确定進入的路徑。