Customized 404 error page in spring-boot

≡放荡痞女 提交于 2019-12-12 02:24:54

问题


I am trying to create a custom error page for invalid URL in SpringMvc (Spring-boot version 1.5.1).

In order to disable the default whitelabel error page I have:

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

My exception handler is:

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);
    }
}

This works in principle. If I go to an invalid URL in the browser I get a JSON which looks like:

{"message":"No such page","error":"NoHandlerFound"}

Instead of the JSON response I would like to show a proper HTML view (similar to the whitelabel page). This should be a template where I can replace the "message" string. How do I go about rendering this view?


回答1:


With Spring Boot & Spring MVC you can create an error folder under resources/public and place your customer error pages. Spring will pick them up.

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

If you're not using Spring MVC you'll have to register the error pages by implementing your own error page registrar.

@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



来源:https://stackoverflow.com/questions/42835504/customized-404-error-page-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!