繁体   English   中英

Spring 引导和自定义 404 错误页面

[英]Spring Boot and custom 404 error page

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

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

此外,我还创建了一个简单的 Thymeleaf 模板:

<!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 错误上我只能看到白屏。

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

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

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

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

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

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

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

Thymleaf 错误.html

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

新的 ErrorPage( HttpStatus.NOT_FOUND , " /404.html ")

/404.html表示重定向URL 路径,而不是模板名称。 由于您坚持使用模板,因此您应该创建一个控制器来处理/404.html并将您的404.html呈现在src/main/resources/templates

@Controller
public class NotFoundController {
    @RequestMapping("/404.html")
    public String render404(Model model) {
        // Add model attributes
        return "404";
    }
}

你也可以用View Controller替换这些只查看渲染器的控制器

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/404.html").setViewName("404");
    }
}

此外,是否可以将模板而不仅仅是静态页面用于自定义错误页面?

是的,这是可能的。 但是 Not Found 页面通常是静态的,使用模板而不是普通的旧 HTML没有多大意义。

如果您像问题中建议的那样使用 Thymeleaf,您可以使用与上一个回复中的模板类似的模板,但适用于 Thymeleaf 而不是 Freemarker。 我还为样式添加了引导程序:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
<title>Error Page</title>
<link href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
<script src="/webjars/jquery/3.2.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron alert-danger">
    <h1>Oops... something went wrong.</h1>
    <h2 th:text="${status + ' ' + error}"></h2>
</div>
</div>
</body>
</html>

您应该将此代码放在名为error.html的文件中,并将其放在 thymeleaf 模板目录中。 无需添加额外的控制器即可工作。

不需要EmbeddedServletContainerCustomizer bean。 只需将相应的错误页面(例如 404.html 的 404)放在公共目录中就足够了(如@brunoid 所指出的)。

另请注意,您还可以放置一个通用的error.html页面,该页面将在您的应用程序遇到错误或异常时显示。

一个简单的例子(在 Freemarker 中) -

<html lang="en">
<head>
</head>
<body>
    <div class="container">
        <div class="jumbotron alert-danger">
            <h1>Oops. Something went wrong</h1>
            <h2>${status} ${error}</h2>
        </div>
    </div>
</body>

</html>

这将显示正确的错误状态和相应的错误消息。 由于您使用的是 Spring Boot,您可以随时覆盖显示在错误页面上的状态和错误消息。

检查类路径中是否存在 thymeleaf,或添加以下代码并重新导入项目。

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

我们必须添加新的

 @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 "error404";
        }
        else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return "error500";
        }
    }
    return "error";
}

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

在此处输入图像描述在 Spring Boot 应用程序中很容易做到。 Spring Boot 为我们完成了所有最重要的事情。

1)在路径 src/main/resources/templates 中创建名为“error”的文件夹

2)接下来在此文件夹中创建html文件,将其保存为'404.html'。

你在这里完成了每一件事。

Spring Boot 如果出现 404 page not found 错误,会自动显示此页面。

注意:在开始之前,请确保您在 pom.xml 中添加了 Thymeleaf 存储库。 xml

Thymeleaf 可以在没有控制器的情况下处理错误。 创建 error.html 到资源文件夹。

弹簧靴 2.6.0

适用于路径src/main/resources/public/error/404.html

<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="jumbotron alert-danger">
        <h1>Oops!</h1>
        <h2>404 Not Found</h2>
    </div>
</div>
</body>

</html>

文件夹树

src
├── main
│   ├── java
│   │   └── com
│   │       └── pxample
│   │           └── pemo
│   │               └── PemoApplication.java
│   └── resources
│       ├── application-dev.properties
│       ├── application-production.properties
│       ├── application.properties
│       ├── application-staging.properties
│       ├── public
│       │   └── error
│       │       └── 404.html
│       ├── static
│       └── templates
└── test
    └── java
        └── com
            └── pxample
                └── pemo
                    └── PemoApplicationTests.java

在这里查看示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM