8.SpringMVC自动配置-Auto-configuration

官方文档:https://docs.spring.io/spring-boot/docs/2.3.9.RELEASE/reference/htmlsingle/#using-boot-auto-configuration

本片文章大部分是翻译SpringBoot的使用手册中的文章,希望大家能有耐心的看文本片文章。

1、Spring MVC Auto-configuration 自动配置

备注:进入到文档直接搜索 Spring MVC Auto-configuration找到自动配置的文档介绍,打开项目双机shift 输入WebMvcAutoConfiguration查看自动配置类中的内容。

The auto-configuration adds the following features on top of Spring’s defaults:

自动配置在 Spring 默认设置的基础上增加了以下特性:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    翻译:包含 ContentNegotiatingViewResolver 和 BeanNameViewResolver bean。

    自动配置ViewResolver(试图解析器:根据方法的返回值得到试图对象(View),试图对象决定如何渲染)

  • Support for serving static resources, including support for WebJars (covered later in this document)).

    翻译:支持服务静态资源,包括对 webjar 的支持。

  • Automatic registration of Converter, GenericConverter, and Formatter beans.

    翻译:转换器、 GenericConverter 和 Formatter bean 的自动注册。

    Converter :类型转换器 -接受参数时转成对象

    Formatter:格式化器:2021.10.27转成date

  • Support for HttpMessageConverters (covered later in this document).

    翻译:对 HttpMessageConverters 的支持。

  • Automatic registration of MessageCodesResolver (covered later in this document).

    翻译:MessageCodesResolver 的自动注册。

  • Static index.html support.

    翻译:静态索引支持。

  • Custom Favicon support (covered later in this document).

    翻译:自定义图标支持。

  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

    翻译:自动使用 ConfigurableWebBindingInitializer bean 。

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

如果您希望保留 Spring Boot MVC 定制并进行更多的 MVC 定制(拦截器、格式化程序、视图控制器和其他特性) ,可以添加您自己的 webmvcrer 类型的@configuration 类,但不要添加@enablewebmvc。

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

如果你想提供自定义的 requestmappinghandler mapping、 requestmappinghandler adapter 或 exceptionhandlerexceptionmvc 定制,你可以声明一个类型为 WebMvcRegistrations 的 bean,并使用它来提供这些组件的自定义实例。

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

如果你想完全控制 Spring MVC,你可以添加你自己的@configuration 注释@enablewebmvc,或者像在@enablewebmvc 的 Javadoc 中描述的那样添加你自己的@configuration 注释 delegatingwebmvcvc 配置。

Spring MVC uses a different ConversionService to the one used to convert values from your application.properties or application.yaml file. The means that Period, Duration and DataSize converters are not available and that @DurationUnit and @DataSizeUnit annotations will be ignored.Spring MVC 使用不同的 ConversionService 来转换 application.properties 或 application.yaml 文件中的值。这意味着 Period、 Duration 和 DataSize 转换器不可用,并且@durationunit 和@datasizeunit 注释将被忽略。If you want to customize the ConversionService used by Spring MVC, you can provide a WebMvcConfigurer bean with an addFormatters method. From this method you can register any converter that you like, or you can delegate to the static methods available on ApplicationConversionService.如果希望自定义 Spring MVC 使用的 ConversionService,可以使用 addformatter 方法提供 webmvcconfigurebean。通过这个方法,您可以注册任何您喜欢的转换器,或者您可以委托给 ApplicationConversionService 上可用的静态方法。

HttpMessageConverters Http//messageconverters

Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses. Sensible defaults are included out of the box. For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available). By default, strings are encoded in UTF-8.

Springmvc 使用 HttpMessageConverter 接口来转换 HTTP 请求和响应。明智的默认设置是开箱即用的。例如,对象可以自动转换为 JSON (通过使用 Jackson 库)或 XML (通过使用 Jackson XML 扩展(如果可用) ,或者通过使用 JAXB (如果 Jackson XML 扩展不可用)。默认情况下,字符串以 UTF-8编码。

If you need to add or customize converters, you can use Spring Boot’s HttpMessageConverters class, as shown in the following listing:

如果你需要添加或者定制转换器,你可以使用 Spring Boot 的 HttpMessageConverters 类,如下面的清单所示:

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;

@Configuration(proxyBeanMethods = false)
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter<?> additional = ...
        HttpMessageConverter<?> another = ...
        return new HttpMessageConverters(additional, another);
    }

}

Any HttpMessageConverter bean that is present in the context is added to the list of converters. You can also override default converters in the same way.

上下文中出现的任何 HttpMessageConverter bean 都将添加到转换器列表中。您也可以用同样的方法覆盖默认转换器。

Custom JSON Serializers and Deserializers 自定义 JSON 序列化器和反序列化器

If you use Jackson to serialize and deserialize JSON data, you might want to write your own JsonSerializer and JsonDeserializer classes. Custom serializers are usually registered with Jackson through a module, but Spring Boot provides an alternative @JsonComponent annotation that makes it easier to directly register Spring Beans.

如果使用 Jackson 对 JSON 数据进行序列化和反序列化,则可能需要编写自己的 JsonSerializer 和 JsonDeserializer 类。自定义序列化程序通常通过一个模块向 Jackson 注册,但 Spring Boot 提供了一个替代的@jsoncomponent 注释,使得直接注册 Spring Beans 变得更加容易。

You can use the @JsonComponent annotation directly on JsonSerializer, JsonDeserializer or KeyDeserializer implementations. You can also use it on classes that contain serializers/deserializers as inner classes, as shown in the following example:

您可以直接在 JsonSerializer、 JsonDeserializer 或 KeyDeserializer 实现上使用@jsoncomponent 注释。也可以在包含序列化器/反序列化器作为内部类的类上使用它,如下面的示例所示:

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer<SomeObject> {
        // ...
    }

    public static class Deserializer extends JsonDeserializer<SomeObject> {
        // ...
    }

}

All @JsonComponent beans in the ApplicationContext are automatically registered with Jackson. Because @JsonComponent is meta-annotated with @Component, the usual component-scanning rules apply.

ApplicationContext 中的所有@jsoncomponent bean 都会自动向 Jackson 注册。因为@jsoncomponent 使用@component 进行了元注释,所以应用了通常的组件扫描规则。

Spring Boot also provides JsonObjectSerializer and JsonObjectDeserializer base classes that provide useful alternatives to the standard Jackson versions when serializing objects. See JsonObjectSerializer and JsonObjectDeserializer in the Javadoc for details.

Spring Boot 还提供了 JsonObjectSerializer 和 JsonObjectDeserializer 基类,它们在序列化对象时为标准 Jackson 版本提供了有用的替代方法。有关详细信息,请参阅 Javadoc 中的 JsonObjectSerializer 和 JsonObjectDeserializer。

1.1MessageCodesResolver

Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver. If you set the spring.mvc.message-codes-resolver-format property PREFIX_ERROR_CODE or POSTFIX_ERROR_CODE, Spring Boot creates one for you (see the enumeration in DefaultMessageCodesResolver.Format).

Springmvc 有一个用于生成错误代码的策略,用于从绑定错误中呈现错误消息: MessageCodesResolver。如果您设置了 Spring.mvc.message-codes-resolver-format 属性 PREFIX _ error _ code 或 POSTFIX _ error _ code,Spring Boot 将为您创建一个属性(参见 DefaultMessageCodesResolver 中的枚举)。格式)。

1.2Static Content 静态内容

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

默认情况下,Spring Boot 从类路径中的/static (或/public 或/resources 或/META-INF/resources)目录或 ServletContext 的根目录提供静态内容。它使用 Spring MVC 中的 ResourceHttpRequestHandler,因此您可以通过添加自己的 webmvcconfigureer 和重写 resourcehandlers 方法来修改该行为。

In a stand-alone web application, the default servlet from the container is also enabled and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. Most of the time, this does not happen (unless you modify the default MVC configuration), because Spring can always handle requests through the DispatcherServlet.

By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to /resources/** can be achieved as follows:

默认情况下,资源映射在/* * 上,但是可以使用 spring.mvc.static-path-pattern 属性对其进行优化。例如,将所有资源转移到/resources/* * 可以做到以下几点:

spring.mvc.static-path-pattern=/resources/**

You can also customize the static resource locations by using the spring.resources.static-locations property (replacing the default values with a list of directory locations). The root Servlet context path, "/", is automatically added as a location as well.

还可以使用 spring.resources.static-locations 属性(用目录位置列表替换默认值)自定义静态资源位置。根 Servlet 上下文路径“/”也会自动作为位置添加。

In addition to the “standard” static resource locations mentioned earlier, a special case is made for Webjars content. Any resources with a path in /webjars/** are served from jar files if they are packaged in the Webjars format.

除了前面提到的“标准”静态资源位置之外,还为 Webjars 内容制作了一个特例。任何路径在/webjar/* * 中的资源如果以 Webjars 格式打包,都可以从 jar 文件中获得。

Do not use the 不要使用src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works 尽管这个目录是一个通用的标准,但是它是可以工作的only 只 with war packaging, and it is silently ignored by most build tools if you generate a jar. 如果你生成一个 jar,大多数构建工具都会默默地忽略它

Spring Boot also supports the advanced resource handling features provided by Spring MVC, allowing use cases such as cache-busting static resources or using version agnostic URLs for Webjars.

Spring Boot 还支持 Spring MVC 提供的高级资源处理特性,允许使用例如缓存破坏静态资源或为 Webjars 使用版本不可知的 url。

To use version agnostic URLs for Webjars, add the webjars-locator-core dependency. Then declare your Webjar. Using jQuery as an example, adding "/webjars/jquery/jquery.min.js" results in "/webjars/jquery/x.y.z/jquery.min.js" where x.y.z is the Webjar version.

若要为 Webjars 使用版本不可知的 url,请添加 Webjars-locator-core 依赖项。然后声明你的 Webjar。以 jQuery 为例,添加”/webjars/jQuery/jQuery.min.js”会导致”/webjars/jQuery/x.y.z/jQuery.min.js”,其中 x.y.z 是 Webjar 版本。

If you use JBoss, you need to declare the webjars-locator-jboss-vfs dependency instead of the 依赖性而不是webjars-locator-core. Otherwise, all Webjars resolve as a 。否则,所有 webjar 将解析为404.

To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as <link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>, in URLs:

为了使用缓存破坏,以下配置为所有静态资源配置缓存破坏解决方案,有效地在 url 中添加内容散列,如 < link href = “/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css”/> :

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
Links to resources are rewritten in templates at runtime, thanks to a ResourceUrlEncodingFilter that is auto-configured for Thymeleaf and FreeMarker. You should manually declare this filter when using JSPs. Other template engines are currently not automatically supported but can be with custom template macros/helpers and the use of the 是自动配置的 Thymeleaf 和 FreeMarker。在使用 jsp 时,应该手动声明这个过滤器。其他模板引擎目前不受自动支持,但可以使用自定义模板宏/帮助程序和ResourceUrlProvider.

When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That is why other strategies are also supported and can be combined. A “fixed” strategy adds a static version string in the URL without changing the file name, as shown in the following example:

当使用例如 JavaScript 模块加载程序动态加载资源时,不能选择重命名文件。这就是为什么其他策略也得到支持,并且可以结合起来。“ fixed”策略在 URL 中添加静态版本字符串,而不更改文件名,如下面的示例所示:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12

With this configuration, JavaScript modules located under "/js/lib/" use a fixed versioning strategy ("/v12/js/lib/mymodule.js"), while other resources still use the content one (<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>).

在这种配置下,位于“/js/lib/”下的 JavaScript 模块使用固定的版本控制策略(“/v12/js/lib/mymodule.js”) ,而其他资源仍然使用内容模块(< link href = "/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css/>)。

See ResourceProperties for more supported options.

有关更多受支持的选项,请参见 ResourceProperties。

This feature has been thoroughly described in a dedicated blog post and in Spring Framework’s reference documentation.这个特性已经在一篇专门的博客文章和 Spring 框架的参考文档中得到了详细的描述。
1.3Welcome Page

Spring Boot supports both static and templated welcome pages. It first looks for an index.html file in the configured static content locations. If one is not found, it then looks for an index template. If either is found, it is automatically used as the welcome page of the application.

Spring Boot 支持静态和模板化欢迎页面。它首先在配置的静态内容位置中查找索引文件。如果没有找到,它就会查找索引模板。如果找到其中任何一个,它将自动用作应用程序的欢迎页面。

1.4Custom Favicon

As with other static resources, Spring Boot looks for a favicon.ico in the configured static content locations. If such a file is present, it is automatically used as the favicon of the application.

与其他静态资源一样,Spring Boot 在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动作为应用程序的图标使用。

Path Matching and Content Negotiation 路径匹配和内容协商

Spring MVC can map incoming HTTP requests to handlers by looking at the request path and matching it to the mappings defined in your application (for example, @GetMapping annotations on Controller methods).

Spring MVC 可以通过查看请求路径并将其与应用程序中定义的映射匹配(例如,Controller 方法上的@getmapping 注释) ,将传入的 HTTP 请求映射到处理程序。

Spring Boot chooses to disable suffix pattern matching by default, which means that requests like "GET /projects/spring-boot.json" won’t be matched to @GetMapping("/projects/spring-boot") mappings. This is considered as a best practice for Spring MVC applications. This feature was mainly useful in the past for HTTP clients which did not send proper “Accept” request headers; we needed to make sure to send the correct Content Type to the client. Nowadays, Content Negotiation is much more reliable.

Spring Boot 默认选择禁用后缀模式匹配,这意味着像“ GET/projects/Spring-Boot”这样的请求。Json”不会与@getmapping (”/projects/spring-boot”)映射匹配。这被认为是 Spring MVC 应用程序的最佳实践。过去,这个特性主要用于 HTTP 客户端,因为它没有发送正确的“ Accept”请求头; 我们需要确保向客户端发送正确的 Content Type。如今,内容协商更加可靠。

There are other ways to deal with HTTP clients that don’t consistently send proper “Accept” request headers. Instead of using suffix matching, we can use a query parameter to ensure that requests like "GET /projects/spring-boot?format=json" will be mapped to @GetMapping("/projects/spring-boot"):

还有其他方法来处理 HTTP 客户端,这些客户端没有始终如一地发送正确的“ Accept”请求头。与使用后缀匹配不同,我们可以使用查询参数来确保像“ GET/projects/spring-boot?Format = json”将被映射到@getmapping (”/projects/spring-boot”) :

spring.mvc.contentnegotiation.favor-parameter=true

# We can change the parameter name, which is "format" by default:
# spring.mvc.contentnegotiation.parameter-name=myparam

# We can also register additional file extensions/media types with:
spring.mvc.contentnegotiation.media-types.markdown=text/markdown

Suffix pattern matching is deprecated and will be removed in a future release. If you understand the caveats and would still like your application to use suffix pattern matching, the following configuration is required:

不推荐使用后缀模式匹配,将在未来的版本中删除。如果你明白这些注意事项,并且仍然希望你的应用程序使用后缀模式匹配,那么需要以下配置:

spring.mvc.contentnegotiation.favor-path-extension=true
spring.mvc.pathmatch.use-suffix-pattern=true

Alternatively, rather than open all suffix patterns, it’s more secure to only support registered suffix patterns:

或者,与其打开所有后缀模式,不如只支持注册后缀模式更安全:

spring.mvc.contentnegotiation.favor-path-extension=true
spring.mvc.pathmatch.use-registered-suffix-pattern=true

# You can also register additional file extensions/media types with:
# spring.mvc.contentnegotiation.media-types.adoc=text/asciidoc
1.5ConfigurableWebBindingInitializer 可配置 webbindinginitializer

Spring MVC uses a WebBindingInitializer to initialize a WebDataBinder for a particular request. If you create your own ConfigurableWebBindingInitializer @Bean, Spring Boot automatically configures Spring MVC to use it.

Springmvc 使用 WebBindingInitializer 为特定请求初始化 WebDataBinder。如果您创建自己的 ConfigurableWebBindingInitializer@Bean,Spring Boot 将自动配置 Spring MVC 以使用它。

1.6Template Engines 模板引擎

As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC integrations.

除了 REST web 服务之外,您还可以使用 springmvc 来提供动态 HTML 内容。Springmvc 支持各种模板技术,包括 Thymeleaf、 FreeMarker 和 jsp。此外,许多其他模板引擎也包括它们自己的 Spring MVC 集成。

Spring Boot includes auto-configuration support for the following templating engines:

Spring Boot 包括下列模板引擎的自动配置支持:

If possible, JSPs should be avoided. There are several 如果可能的话,应该避免使用 jspknown limitations 已知的局限性 when using them with embedded servlet containers. 与内嵌的 servlet 容器一起使用时

When you use one of these templating engines with the default configuration, your templates are picked up automatically from src/main/resources/templates.

当您使用默认配置的这些模板引擎之一时,您的模板将自动从 src/main/resources/templates 中提取。

Depending on how you run your application, your IDE may order the classpath differently. Running your application in the IDE from its main method results in a different ordering than when you run your application by using Maven or Gradle or from its packaged jar. This can cause Spring Boot to fail to find the expected template. If you have this problem, you can reorder the classpath in the IDE to place the module’s classes and resources first. 根据运行应用程序的方式,IDE 可能会以不同的方式排列类路径。在 IDE 中从应用程序的 main 方法运行应用程序的结果与使用 Maven 或 Gradle 或从其打包 jar 运行应用程序的结果不同。这可能导致 Spring Boot 无法找到预期的模板。如果有这个问题,可以重新排列 IDE 中的类路径,以便将模块的类和资源放在第一位
1.7Error Handling 错误处理

By default, Spring Boot provides an /error mapping that handles all errors in a sensible way, and it is registered as a “global” error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a “whitelabel” error view that renders the same data in HTML format (to customize it, add a View that resolves to error).

默认情况下,Spring Boot 提供了一个/error 映射,以合理的方式处理所有错误,并将其注册为 servlet 容器中的“ global”错误页面。对于计算机客户机,它生成一个 JSON 响应,其中包含错误、 HTTP 状态和异常消息的详细信息。对于浏览器客户端,有一个“ whitelabel”错误视图,它以 HTML 格式呈现相同的数据(为了自定义它,添加一个解析为错误的视图)。

There are a number of server.error properties that can be set if you want to customize the default error handling behavior. See the “Server Properties” section of the Appendix.

如果您想自定义默认错误处理行为,可以设置许多 server.error 属性。请参阅附录的“服务器属性”部分。

To replace the default behavior completely, you can implement ErrorController and register a bean definition of that type or add a bean of type ErrorAttributes to use the existing mechanism but replace the contents.

要完全替换默认行为,可以实现 ErrorController 并注册该类型的 bean 定义,或者添加 ErrorAttributes 类型的 bean 来使用现有机制,但替换内容。

The 这个BasicErrorController can be used as a base class for a custom 可以用作自定义的基类ErrorController. This is particularly useful if you want to add a handler for a new content type (the default is to handle .如果您想为新的内容类型添加处理程序(默认是处理text/html specifically and provide a fallback for everything else). To do so, extend 要做到这一点,扩展BasicErrorController, add a public method with a ,添加一个带有@RequestMapping that has a 有一个produces attribute, and create a bean of your new type. 属性,并创建新类型的 bean

You can also define a class annotated with @ControllerAdvice to customize the JSON document to return for a particular controller and/or exception type, as shown in the following example:

您还可以定义一个带有@controlleradvice 注释的类来自定义 JSON 文档以返回特定的控制器和/或异常类型,如下面的示例所示:

@ControllerAdvice(basePackageClasses = AcmeController.class)
public class AcmeControllerAdvice extends ResponseEntityExceptionHandler {

    @ExceptionHandler(YourException.class)
    @ResponseBody
    ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

}

In the preceding example, if YourException is thrown by a controller defined in the same package as AcmeController, a JSON representation of the CustomErrorType POJO is used instead of the ErrorAttributes representation.

在前面的示例中,如果 YourException 是由与 AcmeController 在同一个包中定义的控制器引发的,则使用 CustomErrorType POJO 的 JSON 表示代替 ErrorAttributes 表示。

1.8Custom Error Pages 自定义错误页面

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

如果希望显示给定状态代码的自定义 HTML 错误页面,可以向/error 目录添加文件。错误页面可以是静态 HTML (即添加到任何静态资源目录下) ,也可以通过使用模板构建。文件的名称应该是确切的状态代码或一系列掩码。

For example, to map 404 to a static HTML file, your directory structure would be as follows:

例如,要将404映射到一个静态 HTML 文件,您的目录结构如下:

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

To map all 5xx errors by using a FreeMarker template, your directory structure would be as follows:

要使用 FreeMarker 模板映射所有5xx 错误,目录结构如下:

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.ftlh
             +- <other templates>

For more complex mappings, you can also add beans that implement the ErrorViewResolver interface, as shown in the following example:

对于更复杂的映射,您还可以添加实现 ErrorViewResolver 接口的 bean,如下例所示:

public class MyErrorViewResolver implements ErrorViewResolver {

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request,
            HttpStatus status, Map<String, Object> model) {
        // Use the request or status to optionally return a ModelAndView
        return ...
    }

}

You can also use regular Spring MVC features such as @ExceptionHandler methods and @ControllerAdvice. The ErrorController then picks up any unhandled exceptions.

您还可以使用常规的 Spring MVC 特性,比如@exceptionhandler 方法和@controlleradvice。然后 ErrorController 会拾取任何未处理的异常。

Mapping Error Pages outside of Spring MVC 映射 Spring MVC 外部的错误页面

For applications that do not use Spring MVC, you can use the ErrorPageRegistrar interface to directly register ErrorPages. This abstraction works directly with the underlying embedded servlet container and works even if you do not have a Spring MVC DispatcherServlet.

对于不使用 springmvc 的应用程序,可以使用 ErrorPageRegistrar 接口直接注册 ErrorPages。这个抽象直接与底层的嵌入式 servlet 容器一起工作,即使您没有 Spring MVC DispatcherServlet 也可以工作。

@Bean
public ErrorPageRegistrar errorPageRegistrar(){
    return new MyErrorPageRegistrar();
}

// ...

private static class MyErrorPageRegistrar implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
    }

}
If you register an 如果你注册了一个ErrorPage with a path that ends up being handled by a 这条路最终被一个Filter (as is common with some non-Spring web frameworks, like Jersey and Wicket), then the (正如一些非 spring web 框架(如 Jersey 和 Wicket)常见的那样) ,然后Filter has to be explicitly registered as an 必须明确注册为ERROR dispatcher, as shown in the following example: 分配器,如下面的示例所示:
@Bean
public FilterRegistrationBean myFilter() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter());
    ...
    registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
    return registration;
}

Note that the default FilterRegistrationBean does not include the ERROR dispatcher type.

注意,默认的 FilterRegistrationBean 不包含 ERROR 调度器类型。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苹水相峰

你的打赏是对我最大的肯定

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值