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

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 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?

解决方案

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/

| +

+- resources/

+- public/

+- error/

| +- 404.html

+-

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值