小编典典

spring-boot中的自定义404错误页面

spring-mvc

我正在尝试为SpringMvc(Spring-boot版本1.5.1)中的无效URL创建一个自定义错误页面。

为了禁用默认的whitelabel错误页面,我有:

application.properties

spring.thymeleaf.cache=false
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

我的异常处理程序是:

RestResponseEntityExceptionHandler.java

@ControllerAdvice 
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    public RestResponseEntityExceptionHandler() {
        super();
    }

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error("404 Status Code", ex);
        final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("No such page", null, request.getLocale()), "NoHandlerFound");
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }
}

原则上这是可行的。如果我在浏览器中转到无效的URL,则会得到一个类似于以下内容的JSON:

{“消息”:“没有这样的页面”,“错误”:“ NoHandlerFound”}

我想显示一个正确的HTML视图(类似于whitelabel页面),而不是JSON响应。这应该是一个模板,我可以在其中替换“消息”字符串。我该如何呈现此视图?


阅读 296

收藏
2020-06-01

共1个答案

小编典典

使用Spring Boot&Spring MVC,您可以在resources / public下创建一个错误文件夹,并放置您的客户错误页面。spring会接他们的。

src/
+- main/
   +- java/
   |   + <source code>
   +- resources/
       +- public/
           +- error/
           |   +- 404.html
           +- <other public assets>

如果您不使用Spring MVC,则必须通过实现自己的错误页面注册器来注册错误页面。

@Bean
public ErrorPageRegistrar errorPageRegistrar(){
    return new MyErrorPageRegistrar();
}

private static class MyErrorPageRegistrar implements ErrorPageRegistrar {

    // Register your error pages and url paths.
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
    }

}

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-
features-error-handling-custom-error-pages

2020-06-01