第一种:实现ErrorPageRegistrar
@Configuration
public class ErrorConfigurar 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);
}
}
第二种:SpringBoot2.0之前的写法
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "404.html");
container.addErrorPages(errorPage404);
}
};
}
第三种:SpringBoot2.0之后的写法
@Configuration
public class ErrorPageConfig {
/**
* SpringBoot2.0以上版本WebServerFactoryCustomizer代替之前版本的EmbeddedWebServerFactoryCustomizerAutoConfiguration
*
* @return
*/
//@Bean必须加上
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
// //第一种:java7 常规写法
// return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
// @Override
// public void customize(ConfigurableWebServerFactory factory) {
// ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
// factory.addErrorPages(errorPage404);
// }
// };
//第二种写法:java8 lambda写法
return (factory -> {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
factory.addErrorPages(errorPage404);
});
}
}
🐞标题:SpringBoot2.0实现自定义404页面渲染
👽作者:ruige
🐾地址:https://jjdhhc.com/articles/2021/09/04/1630747043366.html
🙏感恩:谢谢您的打赏与支持!中间图片是我的微信公众号,扫码关注哦!