Customized 404 error page in spring-boot

2019-09-13 02:26发布

问题:

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