Spring Boot自定义错误页面
2017-08-24 16:03
489 查看
Spring Boot默认使用嵌入式Tomcat,默认没有页面来处理404等常见错误。因此,为了给用户最佳的使用体验,404等常见错误需要我们自定义页面来处理。
我们需要用org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer类来实现该功能,在Spring Boot的启动类(main方法所在类)当中,添加如下代码:
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
这是使用Java 8的lambda表达式来简化实现的方式,在代码中创建了三个ErrorPage实例来处理三个通用的HTTP错误状态码,并将他们添加到Container当中。ErrorPage类是一个封装了错误信息的类,它可以在Jetty和Tomcat环境下使用。
这是使用java 7内部类的一个等价实现方式:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
错误页面需要放在Spring Boot web应用的static内容目录下,它的默认位置是:src/main/resources/static,如下图所示:
我们需要用org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer类来实现该功能,在Spring Boot的启动类(main方法所在类)当中,添加如下代码:
@Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return (container -> { ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"); container.addErrorPages(error401Page, error404Page, error500Page); }); }1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
这是使用Java 8的lambda表达式来简化实现的方式,在代码中创建了三个ErrorPage实例来处理三个通用的HTTP错误状态码,并将他们添加到Container当中。ErrorPage类是一个封装了错误信息的类,它可以在Jetty和Tomcat环境下使用。
这是使用java 7内部类的一个等价实现方式:
@Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"); container.addErrorPages(error401Page, error404Page, error500Page); } }; }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
错误页面需要放在Spring Boot web应用的static内容目录下,它的默认位置是:src/main/resources/static,如下图所示:
相关文章推荐
- spring boot 自定义403 404 500 等错误页面
- Spring Boot自定义错误页面
- Spring Boot自定义错误页面,Whitelabel Error Page处理方式
- Spring Boot自定义错误页面,Whitelabel Error Page处理方式
- springboot自定义错误页面
- springboot自定义错误页面
- Spring Boot自定义错误页面
- spring boot 自定义错误页面
- spring boot 源码解析14-默认错误页面处理流程, 自定义,及EnableAutoConfigurationImportSelector处理
- spring boot中自定义错误提示页面
- springboot自定义错误页面(转)
- SpringBoot页面表单请求失败,错误400的解决办法
- 3.Spring Boot + Security初步使用(覆盖配置的两种方式 配置类和XML注入以自定义页面为例)
- spring boot 下 500 404 错误页面处理
- Spring Boot学习笔记-错误处理及自定义
- 全局异常处理类的定义与错误页面实现(基于SpringBoot)
- springboot使用之四:错误页面404处理建议
- springboot默认错误页面及静态资源
- SpringBoot中jsp页面调用iframe标签报Whitelabel Error Page 错误
- spring boot 下 500 404 错误页面处理