Spring Boot不显示自定义错误页 [英] spring boot doesn't shows custom error pages

查看:35
本文介绍了Spring Boot不显示自定义错误页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

并在Application.yml:

中添加此配置
server:
  error:
    whitelabel:
      enabled: false

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

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

如何解决此问题?我也在谷歌上搜索了一下,但没有找到任何可以帮助的东西。

推荐答案

尝试使用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不显示自定义错误页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆