Spring Boot 和自定义 404 错误页面 [英] Spring Boot and custom 404 error page

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

问题描述

在我的 Spring Boot 应用程序中,我正在尝试配置自定义错误页面,例如对于 404,我在应用程序配置中添加了以下 Bean:

@Bean公共 EmbeddedServletContainerCustomizer containerCustomizer() {返回新的 EmbeddedServletContainerCustomizer() {@覆盖公共无效定制(ConfigurableEmbeddedServletContainer容器){container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));}};}

此外,我创建了以下简单的 Thymeleaf 模板:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"><头><title>404 Not Found</title><meta charset="utf-8"/><身体><h3>404 未找到</h3><h1 th:text="${errorCode}">404</h1><p th:utext="${errorMessage}">错误 java.lang.NullPointerException</p><a href="/" th:href="@{/}">返回首页</a>

并将其添加到 /resources/templates/ 文件夹中.现在出现 404 错误,我只能看到白屏.

我做错了什么以及如何正确设置我的 404 页面?另外,对于自定义错误页面,是否可以使用模板而不仅仅是静态页面?

解决方案

您正在使用 Thymeleaf,并且 Thymeleaf 可以在没有控制器的情况下处理错误.

对于通用错误页面,此 Thymeleaf 页面需要命名为 error.html
并且应该放在 src/main/resources > 下模板 >error.html

对于特定的错误页面,您需要在名为error的文件夹中创建名为http错误代码的文件,例如:src/main/resources/templates/error/404.html.>

In my Spring Boot application, I'm trying to configure custom error pages, for example for 404, I have added a following Bean to my application configuration:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
        }
    };
}

Also, I have created a following simple Thymeleaf template:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>404 Not Found</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <h3>404 Not Found</h3>
        <h1 th:text="${errorCode}">404</h1>
        <p th:utext="${errorMessage}">Error java.lang.NullPointerException</p>
        <a href="/" th:href="@{/}">Back to Home Page</a>
    </body>
</html>

and added it into /resources/templates/ folder. Right now on the 404 error I can see only white screen.

What am I doing wrong and how to correctly setup my 404 page? Also, is it possible to use templates and not only static pages for custom error pages?

解决方案

You're using Thymeleaf, And Thymeleaf can handle error without a controller.

For a generic error page this Thymeleaf page need to be named as error.html
and should be placed under src/main/resources > templates > error.html

For specific error pages, you need to create files named as the http error code in a folder named error, like: src/main/resources/templates/error/404.html.

这篇关于Spring Boot 和自定义 404 错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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