第一种写法

实现ErrorPageRegistrar,404.html放在项目的webapp文件夹中

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {

@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage[] errorPages = new ErrorPage[2];
errorPages[0] = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
errorPages[1] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

registry.addErrorPages(errorPages);
}
}

第二种写法

Spring Boot2.0 之后的写法,404.html文件放在resources的static文件夹中

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class ErrorPageConfig {
@Bean
public WebServerFactoryCustomizer webServerFactoryCustomizer() {
//第二种写法:java8 lambda写法
return (factory -> {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
factory.addErrorPages(errorPage404);
});

}
}