我想在SpringMvc(Spring-boot版本1.5.1)中为无效URL创建一个自定义错误页面。在弹簧引导中定制404错误页
为了禁用默认的白色标签的错误页面,我有:
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”}
相反的JSON响应我想展示一个合适的HTML视图(类似于白标签页)。这应该是一个可以替换“消息”字符串的模板。我如何去渲染这个视图?
我在使用Spring MVC与thymeleaf,并试图把和的error.html页面404.html在/资源/公/错误/中/资源/模板和/资源/模板/错误/但显然他们无法找到。还有什么需要做这项工作? – user1583209
从您的属性文件中删除server.error.whitelabel.enabled = false。 – jmw5598
工作。现在我只需要弄清楚如何将请求url导入到视图中。 – user1583209