43. Spring mvc error handling based on springboot automatic configuration means that after the demo project reports an error, it jumps to a custom error page

Spring MVC error handling: Spring MVC error handling based on SpringBoot automatic configuration.

It means that there is an error when accessing the method, and then a custom error page is displayed.

★ Two error handling methods

  • Method 1: Based on the error handling method of Spring Boot automatic configuration, the error handling behavior can be configured only through the property file.
    Just provide a custom error page.

  • Method 2: Use AOP-based exception handling mechanisms such as @ResponseStatus, @ExceptionHandler, @ControllerAdvice, etc.
    This is directly based on Spring MVC exception handling mechanism for error handling.

method one:

The following describes method 1:
error handling method based on Spring Boot automatic configuration. Error handling behavior can be configured through the properties file. Just provide a custom error page.

★ Automatic configuration of error handling

默认提供了一个/error映射来处理所有的错误,并将它注册为Servlet容器的全局错误页面。

 - 对于程序客户端(比如Http Client或RESTful客户端),
   它会生成一个具有错误详情,HTTP状态和异常信息的JSON响应。

 - 对于普通浏览器,它会生成一个White Label(白标)页面,该页面以HTML格式显示同样的错误信息。 

 这就是为何,前面看到程序一旦出错,总可以在浏览器中看到一个白标错误页面。

 这是Spring Boot默认、自动提供的错误呈现。

★ Configure the attributes to be included in the error object.

 Spring Boot使用ErrorProperties类来读取错误处理有关的配置信息。

 public class ErrorProperties {

@Value("${error.path:/error}")
private String path = "/error";

    // 指定错误对象是否包含exception" attribute.
private boolean includeException;

    // 指定错误对象是否包含trace属性.
private IncludeAttribute includeStacktrace = IncludeAttribute.NEVER;

    // 指定错误对象是否包含"message属性.
private IncludeAttribute includeMessage = IncludeAttribute.NEVER;

    // 指定错误对象是否包含errors属性.
private IncludeAttribute includeBindingErrors = IncludeAttribute.NEVER;

private final Whitelabel whitelabel = new Whitelabel();

错误对象会直接传给上面程序客户端(JSON响应)或浏览器的白标页面。

【换而言之】,你能在程序客户端中看到的JSON响应数据,以及在浏览器的白标页面中能看到错误信息,

 其实都是可以配置的,该配置就是由此处的ErrorProperties 负责设置的。

 因此可进行如下配置:

 # 指定包含异常类
 server.error.include-exception=true
 # 指定一直包含BindingErrors
 server.error.include-binding-errors=always
 # 指定启用白标页面(这是默认值)
 server.error.whitelabel.enabled=true

★ Custom error page

 ▲ 都要放在/error目录下。

 - 静态错误页面, 静态资源目录下的/error子目录中。
                  static/error或者public/error目录中。

 - 动态错误页面,应该放在templates/error目录中。

 ▲ 错误页面的命名

  错误代码.html(静态)或 错误代码.<页面模板的扩展名>——此处的扩展名取决于你用什么样的页面模板技术。

  Spring Boot的错误页面不仅可支持精确匹配,比如404.ext或404.html将作为404错误的错误页面。

  还可支持模糊匹配,比如定义文件名为“4xx.<ext>或4xx.html”的页面,它将可作为所有4xx错误码的错误页面。

  错误对象默认支持的属性,可通过DefaultErrorAttributes来查看。

★【To summarize】

 Spring Boot自动配置的错误处理,可以说非常简单。

 (1) 在application.properties文件中配置错误对象要包含哪些属性。

 (2) 在静态资源路径中的error子目录中定义静态错误页面,或在templates目录的error子目录中定义动态错误页面模板。

  这样Spring Boot即可呈现自定义出错误处理页面。

Code demo:

1. After the demo project reports an error, jump to the customized error page

First, write a method. After the access fails, the default error page that jumps to looks like this.
But the page is not friendly to ordinary people, so it needs to be optimized.
Insert image description here

To customize the error page, you need to do the following:

In the configuration class, specify which properties should be included in the returned error object

Insert image description here

Next, customize the error page:
the error page is divided into static page and dynamic page.
Static page: A hard-coded page that does not need to obtain any value.
Dynamic pages: You can get some error messages, which are dynamic pages.

Important: Custom error pages need to be placed in the error folder.

  • Static error page, in the /error subdirectory under the static resource directory.
    in the static /error or public/error directory.

  • Dynamic error pages should be placed in the templates/error directory.

dynamic error page

Now create a dynamic error page:
Create a dynamic error page in the templates/error directory. Some attribute values ​​​​in the page come from the DefaultErrorAttributes class, which are the default attributes supported by the DefaultErrorAttributes error object. You can get some information about the error.
Insert image description here

The attributes supported by the error object by default can be viewed through the DefaultErrorAttributes class.
Insert image description here

Test:
Because springboot’s default error jump mapping path is /error, when an error occurs, it will look for the /error folder by default.

From this ErrorProperties class, we can see the default mapping path after an error occurs.
Insert image description here
Knowledge point:
Spring Boot's error page not only supports exact matching, for example, 404.ext or 404.html will be used as the error page for 404 errors.
Fuzzy matching can also be supported, such as defining a page with a file name of "4xx. or 4xx.html", which will serve as the error page for all 4xx error codes.

It can be seen that when a 500 error occurs in the access method, it will automatically jump to the page starting with 5xx.

Insert image description here

Static error page

We can access it at will. If there is no such method, this page will appear. At this time, we can make a static error page to display.
Insert image description here

important point:

  • Static error page, in the /error subdirectory under the static resource directory.
    in the static /error or public/error directory.

Insert image description here

Effect:
Insert image description here

添加thymeleaf需要的jar包

        <!--  添加 thymeleaf 依赖 ,整合 thymeleaf 的 starter  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- jquery 的 web jar 包 -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.0</version>
        </dependency>
        <!-- bootstrap 的 web jar 包 -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.6.0</version>
        </dependency>
        <!--支持版本无关的 Web Jar ,前端引入 Web Jar 相关的 jquery、bootstrap 依赖可以不用写版本号-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
            <version>0.47</version>
        </dependency>

前端页面需要引入的一些js样式

    <!--  引入css样式,用 link 元素  ,  stylesheet 样式单 , .gz表示是打包的,但是springboot会自动解包 -->
    <!--  引入 Bootstrap 的 Web Jar 中的 CSS 样式  -->
    <link rel="stylesheet" th:href="@{'/webjars/bootstrap/css/bootstrap.min.css'}">
    <!--  jquery 放在 bootstrap 前面,因为 bootstrap 需要依赖到 jquery  -->
    <!--  引入 jQuery 的 Web Jar 中的 js 脚本  -->
    <script type="text/javascript" th:src="@{'/webjars/jquery/jquery.min.js'}"></script>
    <!--  引入 Bootstrap 的 Web Jar 中的 js 脚本  -->
    <script type="text/javascript" th:src="@{'/webjars/bootstrap/js/bootstrap.bundle.min.js'}"></script>
    <!--  引入 popper 的 Web Jar 中的 Js 脚本  -->
    <script type="text/javascript" th:src="@{'/webjars/popper.js/umd/popper.min.js'}"></script>

おすすめ

転載: blog.csdn.net/weixin_44411039/article/details/132587339