Java Spring Boot 和自定义 404 错误页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37398385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:16:57  来源:igfitidea点击:

Spring Boot and custom 404 error page

javaspringspring-mvcspring-bootthymeleaf

提问by brunoid

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. Right now on the 404 error I can see only white screen.

并将其添加到/resources/templates/文件夹中。现在在 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?

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

采纳答案by GoutamS

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
and should be placed under src/main/resources > templates > error.html

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

Thymleaf 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.

回答by Ali Dehghani

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

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

That /404.htmlrepresents the URL Path to Redirect, not the template name. Since, you insist to use a template, you should create a controller that handles the /404.htmland renders your 404.htmlresides in src/main/resources/templates:

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

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 HTMLswouldn't make that much of a sense.

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

回答by brunoid

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 /errorfolder. 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.

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>

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

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

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

回答by Naiyer

There is no need for the EmbeddedServletContainerCustomizerbean. 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).

不需要EmbeddedServletContainerCustomizer豆子。只需将相应的错误页面(例如 404.html,如果是 404)放在 public 目录中就足够了(如@brunoid 所指出的)。

Also note that you can also put a generic error.htmlpage 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,您可以随时覆盖显示在错误页面上的状态和错误消息。

回答by OlgaMaciaszek

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. I have also added bootstrap for the styling:

如果您像问题中建议的那样使用 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>

You should place this code in a file called error.htmland place it in your thymeleaf templates directory. There is no need to add an additional controller for it to work.

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

回答by sujoydutta

Thymeleaf can handle error without a controller. create error.html to resources folder.

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

回答by Vipul Gulhane

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

回答by Himadri Mandal

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>

回答by pranav patil

enter image description hereIt's very easy to do in Spring Boot Application. Spring Boot all most done all thing for us.

在此处输入图像描述在 Spring Boot 应用程序中很容易做到。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. xml

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