Spring Boot Web Error Page处理

来源:互联网 发布:634741网络语什么意思 编辑:程序博客网 时间:2024/05/21 10:57

Spring Boot默认是whitelabel error page. 其实我们可以自己处理,由于时间有限,所以就简单说明一下方法。

首先配置

@Configurationpublic class ErrorPageConfig  {    @Bean    public EmbeddedServletContainerCustomizer containerCustomizer() {        return new EmbeddedServletContainerCustomizer() {            public void customize(ConfigurableEmbeddedServletContainer container) {                ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/400.html");                ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404/");                ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");                container.addErrorPages(error400Page, error401Page, error404Page, error500Page);            }        };    }}

细心的朋友会看到,404不是html, 这儿为了掩饰,所以用了两种方法,如果是html的方法,需要将html文件放到resources/static目录下。404处理方式,就需要我们自己处理/404请求,与一般的Controller中处理Request类似。如下:

@RequestMapping("404")    public String error404() {        return "error404";    }

用到了模版,所以需要在resources/templates目录下创建error404.html文件
其实配置的时候,也可以用继承的方式:

@Configurationpublic class ErrorPageConfig implements EmbeddedServletContainerCustomizer {    @Override    public void customize(ConfigurableEmbeddedServletContainer container) {        container.addErrorPages(                new ErrorPage(HttpStatus.BAD_REQUEST, "/4O0.html"),                new ErrorPage(HttpStatus.UNAUTHORIZED, "/4O1.html"),                new ErrorPage(HttpStatus.NOT_FOUND, "/404/"),                new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html")        );    }}

关于异常的处理可以参看:http://blog.didispace.com/springbootexception/

0 0