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

use*_*209 0 model-view-controller exception-handling spring-mvc spring-boot

我试图在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
Run Code Online (Sandbox Code Playgroud)

我的异常处理程序是:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这原则上有效.如果我在浏览器中找到无效的URL,我会得到一个类似于以下内容的JSON:

{"message":"没有这样的页面","错误":"NoHandlerFound"}

我希望显示一个正确的HTML视图(类似于whitelabel页面),而不是JSON响应.这应该是一个模板,我可以替换"消息"字符串.如何渲染此视图?

Jas*_*ite 8

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

src/
+- main/
   +- java/
   |   + <source code>
   +- resources/
       +- public/
           +- error/
           |   +- 404.html
           +- <other public assets>
Run Code Online (Sandbox Code Playgroud)

如果您没有使用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"));
    }

}
Run Code Online (Sandbox Code Playgroud)

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