【问题标题】:Spring boot 2.1 error.html page not showing [duplicate]Spring boot 2.1 error.html 页面未显示[重复]
【发布时间】:2019-07-19 08:01:27
【问题描述】:

我使用的是 spring-boot 2.1.3,我想添加一个错误页面作为后备。我尝试在模板文件夹下添加一个error.html,但没有成功。

还尝试添加 ErrorController 并为每种错误类型分类页面,但它也不起作用。

我还需要做其他配置吗?

提前致谢。

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-security


    【解决方案1】:

    直接在资源/模板中添加 error.html 对我也不起作用。 所以我创建了一个自定义的错误控制器并将error.html添加到资源/静态文件夹中。

    来源:https://www.baeldung.com/spring-boot-custom-error-page

    @Controller
    public class CustomizedErrorController implements ErrorController  {
    
        @RequestMapping("/error")
        public String handleError() {
            return "error.html";
        }
    
        @Override
        public String getErrorPath() {
            return "/error";
        }
    }
    

    【讨论】:

      【解决方案2】:

      除了关闭 Whitelabel 错误页面之外,您还可以通过将此属性添加到属性文件来实现:

      server.error.whitelabel.enabled=false
      

      确保您在以下文件夹中有静态错误页面(即 404.html):

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

      来源:Spring Boot docs

      【讨论】:

      • 感谢您的回复 我已按照您的要求整理了文件,但仍然没有任何变化
      • @motawfik 你能详细说明一下吗?您在浏览器上究竟看到了什么?您是否将属性添加到属性文件中?
      • { timestamp: 1551216779662, status: 404, error: "Not Found", message: "No message available", path: "/ss" } 这以 JSON 格式返回,是的,我添加了属性
      • @motawfik 您将不得不编辑您的问题并向我们展示您的控制器/或您如何处理视图...看来您没有使用默认值!?
      • 不是我没有使用控制器来处理错误,我正在尝试使用默认的 error.html 页面作为后备
      【解决方案3】:

      我唯一能想到的(没有提供任何代码示例)是 /error 可能没有查看权限。请尝试在SecurityConfigurations中设置权限,允许/error被所有人访问。

      http.authorizeRequests().antMatchers("/error").permitAll();
      

      【讨论】:

      • 感谢您的回复,我已在 antMatchers 中添加了错误但仍然没有更改,以及 application.properties 中的 server.error.whitelabel.enabled=false
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2021-10-31
      • 2018-02-26
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      相关资源
      最近更新 更多