Spring Boot不显示自定义错误页面。

6

我向我的使用spring boot 2.3.1.RELEASE的项目中添加了 spring-boot-starter-thymeleaf 依赖,并在 src/main/resources/templates 中放置了名为 error.html 和其他自定义错误页面文件,正如下面图片所示:

Custom error page files

并且在 application.yml 文件中添加了以下配置:

server:
  error:
    whitelabel:
      enabled: false

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

但是,不幸的是,当出现错误时,例如404错误,我看到了下面这个页面!

404 error page

如何解决这个问题? 我也搜索了一些资料,但是没有找到任何有用信息。

3个回答

4

尝试使用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"));
    }
}

还有ErrorController:

@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";
    }
}

我的结构与这个相同,它可以正常工作:

enter image description here

例如:自定义错误消息

注意:在我的application.yml中没有任何关于错误处理的属性。


使用Spring Boot 2.3和JSP with Tiles - 这是唯一有效的方法。 - dipan66

1

0
将以下内容翻译成中文,与编程有关,请仅返回翻译后的文本:
  1. 在application.yml/application.properties中添加以下配置:

    • server.error.path=/error
  2. 在error路径下创建您的错误页面

    • error/400.html
    • error/500.html
    • error/error.html
  3. 创建实现ErrorController的类:

    @Controller

    public class MyErrorController implements ErrorController {

    @RequestMapping("/error")
    

    public String handleError(HttpServletRequest request) {

     Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); 
    
     if (status != null) {
         Integer statusCode = Integer.valueOf(status.toString());
    
         if(statusCode == HttpStatus.NOT_FOUND.value()) {
             return "/error/404";
         }
         else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
             return "/error/500";
         }
     }
     return "/error/error";
    

    }

    }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接