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

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

问题描述

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

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

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

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>

并将其添加到 / resources / templates / 文件夹。现在在404错误上我只能看到白屏。

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

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

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?

推荐答案

在Spring Boot 1.4.x中你可以添加自定义错误页面

In Spring Boot 1.4.x you can add a custom error page:


如果你想显示给定状态代码的自定义HTML错误页面,您将文件添加到 / error 文件夹。错误页面可以是静态HTML(即添加到任何静态资源文件夹下)或使用模板构建。该文件的名称应该是确切的状态代码或系列掩码。

If you want to display a custom HTML error page for a given status code, you add a file to an /error folder. Error pages can either be static HTML (i.e. added under any of the static resource folders) or built using templates. The name of the file should be the exact status code or a series mask.

例如,要将404映射到静态HTML文件,您的文件夹结构将如下所示:

For example, to map 404 to a static HTML file, your folder structure would look like this:

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


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

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