【问题标题】:catch 404 error spring boot to return custom html捕获 404 错误 spring boot 以返回自定义 html
【发布时间】:2019-01-23 08:13:00
【问题描述】:

如何在应用程序中捕获 404 错误并呈现像 index.html 这样的自定义 html?我不想使用 /error 文件夹中的页面。

例如,如果我要求 http://localhost:8080/test 并且没有用于测试的映射,我的应用程序应该在 /resources/template 文件夹中呈现 index.html

谢谢

****编辑****

这样解决了,不好的是即使更改了getErrorPath返回值,我也无法更改请求映射的路径。

@Controller
public class MyCustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        return "globalerrorview";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

【问题讨论】:

  • 您是否使用 thymeleaf / 类似库进行模板化?
  • @akhilRao 是的,抱歉,添加为标签

标签: spring-boot spring-mvc thymeleaf


【解决方案1】:

有很多方法可以实现自定义错误页面。一种简单的方法是使用/resources/public/error/404.html,这在您的情况下是不需要的。

选项:1 你能试试配置ControllerAdvice吗?

application.properties
    spring.mvc.throw-exception-if-no-handler-found=true
----------------------
@ControllerAdvice
class YourApplicationExceptionHandler {

    @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleNoHandlerFoundException() {
        return new ModelAndView("viewName");
    }
} 

选项 2: 如果您为错误定义了任何其他路径,您可以简单地更改 /error 路径。在您的 Controller 中定义相应的路径映射和路由到自定义视图。

server.error.path=/yourcustomerrorpath

选项 3:使用 ErrorController

@Controller
public class MyCustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        return "globalerrorview";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}


【讨论】:

  • Haran 我试过了,但看起来没什么,我也尝试在函数中记录一些东西,但看起来它没有使用
  • 看到使用 controllerAdvice 这给了我:异常处理 ErrorPage[errorCode=0, location=/error]
  • 不确定是否要显示特定于代码 (401,404,403) 的错误页面的确切要求。对于全局 /error 路径,您可以尝试选项 3。
  • 在询问之前我已经尝试过使用选项 3,但看起来甚至没有调用 getErrorPath,我尝试将日志放入其中但没有发生任何事情......
  • 好的,所以,看起来 getErrorPath 不起作用,如果我返回 "/" 而不是 "/error" 什么也没发生,它总是会搜索 /error
猜你喜欢
  • 2020-11-13
  • 2015-09-04
  • 2018-07-15
  • 2014-11-30
  • 2017-08-07
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多