简体   繁体   English

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

[英]Spring Boot and custom 404 error page

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:在我的 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"));
        }
    };
}

Also, I have created a following simple Thymeleaf template:此外,我还创建了一个简单的 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>

and added it into /resources/templates/ folder.并将其添加到/resources/templates/文件夹中。 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?我做错了什么以及如何正确设置我的 404 页面? Also, is it possible to use templates and not only static pages for custom error pages?另外,是否可以使用模板而不仅仅是 static 页面用于自定义错误页面?

In Spring Boot 1.4.x you can add a custom error page :在 Spring Boot 1.4.x 中,您可以添加自定义错误页面

If you want to display a custom HTML error page for a given status code, you add a file to an /error folder.如果要为给定状态代码显示自定义 HTML 错误页面,请将文件添加到/error文件夹。 Error pages can either be static HTML (ie added under any of the static resource folders) or built using templates.错误页面可以是静态 HTML(即添加到任何静态资源文件夹下)或使用模板构建。 The name of the file should be the exact status code or a series mask.文件的名称应该是确切的状态代码或系列掩码。

For example, to map 404 to a static HTML file, your folder structure would look like this:例如,要将 404 映射到静态 HTML 文件,您的文件夹结构将如下所示:

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

You're using Thymeleaf, And Thymeleaf can handle error without a controller.您正在使用 Thymeleaf,并且 Thymeleaf 可以在没有控制器的情况下处理错误。

For a generic error page this Thymeleaf page need to be named as error.html对于通用错误页面,此 Thymeleaf 页面需要命名为error.html
and should be placed under src/main/resources > templates > error.html并且应该放在src/main/resources > templates > error.html

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

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

That /404.html represents the URL Path to Redirect , not the template name. /404.html表示重定向URL 路径,而不是模板名称。 Since, you insist to use a template, you should create a controller that handles the /404.html and renders your 404.html resides in src/main/resources/templates :由于您坚持使用模板,因此您应该创建一个控制器来处理/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";
    }
}

You could also replace these just view render-er controllers with a View Controller :你也可以用View Controller替换这些只查看渲染器的控制器

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

Also, is it possible to use templates and not only static pages for custom error pages ?此外,是否可以将模板而不仅仅是静态页面用于自定义错误页面?

Yes, it's possible.是的,这是可能的。 But Not Found pages are usually static and using a template instead of Plain Old HTMLs wouldn't make that much of a sense.但是 Not Found 页面通常是静态的,使用模板而不是普通的旧 HTML没有多大意义。

If you are using Thymeleaf like suggested in the question, you could use a template similar to the one from the previous reply, but appropriate for Thymeleaf rather than Freemarker.如果您像问题中建议的那样使用 Thymeleaf,您可以使用与上一个回复中的模板类似的模板,但适用于 Thymeleaf 而不是 Freemarker。 I have also added bootstrap for the styling:我还为样式添加了引导程序:

<!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>

You should place this code in a file called error.html and place it in your thymeleaf templates directory.您应该将此代码放在名为error.html的文件中,并将其放在 thymeleaf 模板目录中。 There is no need to add an additional controller for it to work.无需添加额外的控制器即可工作。

There is no need for the EmbeddedServletContainerCustomizer bean.不需要EmbeddedServletContainerCustomizer bean。 Simply putting the corresponding error page (such as 404.html in case of 404) in the public directory should be enough (as pointed by @brunoid).只需将相应的错误页面(例如 404.html 的 404)放在公共目录中就足够了(如@brunoid 所指出的)。

Also note that you can also put a generic error.html page that'll get displayed whenever your application encounters an error or exception.另请注意,您还可以放置一个通用的error.html页面,该页面将在您的应用程序遇到错误或异常时显示。

A simple example (in Freemarker) -一个简单的例子(在 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>

This'll display proper error status and corresponding error message.这将显示正确的错误状态和相应的错误消息。 And since you are using Spring Boot, you can always override the status and error messages that get displayed on your error page.由于您使用的是 Spring Boot,您可以随时覆盖显示在错误页面上的状态和错误消息。

Check if you have thymeleaf present in the classpath, or add below code and reimport the project.检查类路径中是否存在 thymeleaf,或添加以下代码并重新导入项目。

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

We have to add new我们必须添加新的

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

enter image description here It's very easy to do in Spring Boot Application.在此处输入图像描述在 Spring Boot 应用程序中很容易做到。 Spring Boot all most done all thing for us. Spring Boot 为我们完成了所有最重要的事情。

1)In Path src/main/resources/templates make folder which has name 'error' 1)在路径 src/main/resources/templates 中创建名为“error”的文件夹

2)Next create html file in this folder, save it as '404.html'. 2)接下来在此文件夹中创建html文件,将其保存为'404.html'。

You done evey thing here.你在这里完成了每一件事。

Spring Boot Automatically show this page if it got 404 page not found error. Spring Boot 如果出现 404 page not found 错误,会自动显示此页面。

Note: Before going to this, make sure that you added Thymeleaf repository in your pom.注意:在开始之前,请确保您在 pom.xml 中添加了 Thymeleaf 存储库。 xml xml

Thymeleaf can handle error without a controller. Thymeleaf 可以在没有控制器的情况下处理错误。 create error.html to resources folder.创建 error.html 到资源文件夹。

spring boot 2.6.0弹簧靴 2.6.0

works with path src/main/resources/public/error/404.html适用于路径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>

folder tree文件夹树

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

see example here 在这里查看示例

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

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