【问题标题】:spring boot doesn't shows custom error pagesspring boot 不显示自定义错误页面
【发布时间】:2020-10-24 21:37:54
【问题描述】:

我使用 spring boot 2.3.1.RELEASEspring-boot-starter-thymeleaf 依赖项添加到我的项目中,并将error.html 文件放在src/main/resources/templates 中,名称为error.html and other custom error pages inside src/main/resources/templates /error` 如下图所示:

并在 application.yml 中添加此配置:

server:
  error:
    whitelabel:
      enabled: false

并通过将@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class}) 添加到Application 类中来排除ErrorMvcAutoConfiguration

但是,不幸的是,当发生错误时,我会在下面看到这个页面,例如 404 错误!

我该如何解决这个问题?我也用谷歌搜索过,但没有找到任何帮助。

【问题讨论】:

    标签: java spring spring-boot error-handling customization


    【解决方案1】:

    尝试使用WebServerFactoryCustomizer:

    @Configuration
    public class WebConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    
        @Override
        public void customize(ConfigurableServletWebServerFactory factory) {
            factory.addErrorPages(
                    new ErrorPage(HttpStatus.FORBIDDEN, "/403"),
                    new ErrorPage(HttpStatus.NOT_FOUND, "/404"),
                    new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
        }
    }
    

    和错误控制器:

    @Controller
    public class ErrorController {
    
        @GetMapping("/403")
        public String forbidden(Model model) {
            return "error/403";
        }
    
        @GetMapping("/404")
        public String notFound(Model model) {
            return "error/404";
        }
    
        @GetMapping("/500")
        public String internal(Model model) {
            return "error/500";
        }
    
        @GetMapping("/access-denied")
        public String accessDenied() {
            return "error/access-denied";
        }
    }
    

    我有相同的结构,它对我有用:

    示例:Customize the Error Messages

    PS:在我的 application.yml 我没有任何用于错误处理的属性

    【讨论】:

    • 使用 Spring boot 2.3 和 JSP with Tiles - 这是唯一有效的方法。
    【解决方案2】:

    您无需排除ErrorMvcAutoConfiguration。 只需将错误页面放在这些地方即可。

    另见:

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 2014-11-30
      • 2018-02-11
      • 2017-08-07
      • 2013-09-12
      • 1970-01-01
      • 2018-05-07
      • 2017-02-07
      • 2015-11-19
      相关资源
      最近更新 更多