SpringMVC官方文档翻译中英文对照

Web on Servlet Stack

Version 5.2.3.RELEASE

This part of the documentation covers support for Servlet-stack web applications built on the Servlet API and deployed to Servlet containers. Individual chapters include Spring MVCView TechnologiesCORS Support, and WebSocket Support. For reactive-stack web applications, see Web on Reactive Stack.

本文介绍了对基于ServletAPI构建并部署到Servlet容器的Servlet-stack web应用程序的支持。章节包括Spring MVCView TechnologiesCORS Support, 和 WebSocket Support。有关reactive-stack web应用程序,请参阅Web on Reactive Stack

1. Spring Web MVC

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, “Spring Web MVC,” comes from the name of its source module (spring-webmvc), but it is more commonly known as “Spring MVC”.

Spring Web MVC是基于Servlet API构建的原始Web框架,并且从一开始就已包含在Spring框架中。 正式名称“ Spring Web MVC”来自其源模块的名称(spring-webmvc),但通常称为“ Spring MVC”。

Parallel to Spring Web MVC, Spring Framework 5.0 introduced a reactive-stack web framework whose name, “Spring WebFlux,” is also based on its source module (spring-webflux). This section covers Spring Web MVC. The next section covers Spring WebFlux.

与Spring Web MVC并行,Spring Framework 5.0引入了一个reactive-stack Web框架,其名称“ Spring WebFlux”也是基于其源模块(spring-webflux)。 本节介绍Spring Web MVC。 下一节介绍Spring WebFlux。 

For baseline information and compatibility with Servlet container and Java EE version ranges, see the Spring Framework Wiki.
有关基线信息以及与Servlet容器和Java EE版本范围的兼容性,请参见Spring Framework Wiki

1.1. DispatcherServlet

WebFlux

Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows.

跟许多其他Web框架一样,Spring MVC围绕前端控制器模式进行设计,其中核心Servlet DispatcherServlet为请求处理提供共享算法,而实际工作由可配置的委托组件执行。 该模型非常灵活,并支持多种工作流程。

The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling, and more.

与任何Servlet一样,DispatcherServlet必须根据Servlet规范通过使用Java配置或在web.xml中进行声明和映射。 反过来,DispatcherServlet使用Spring配置来发现请求映射,视图解析,异常处理等所需的委托组件。

The following example of the Java configuration registers and initializes the DispatcherServlet, which is auto-detected by the Servlet container (see Servlet Config):

以下示例使用Java配置注册与初始化DispatcherServlet,由Servlet容器自动检测(请参阅Servlet Config):

Java

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletCxt) {

        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);
        ac.refresh();

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}
 

In addition to using the ServletContext API directly, you can also extend AbstractAnnotationConfigDispatcherServletInitializer and override specific methods (see the example under Context Hierarchy).

除了直接使用ServletContext API外,您还可以继承AbstractAnnotationConfigDispatcherServletInitializer并重写特定方法(请参见Context Hierarchy下的示例)。

The following example of web.xml configuration registers and initializes the DispatcherServlet:

以下示例使用web.xml配置注册并初始化DispatcherServlet:

<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>
 

Spring Boot follows a different initialization sequence. Rather than hooking into the lifecycle of the Servlet container, Spring Boot uses Spring configuration to bootstrap itself and the embedded Servlet container. Filter and Servlet declarations are detected in Spring configuration and registered with the Servlet container. For more details, see the Spring Boot documentation.

 

Spring Boot遵循不同的初始化顺序。 Spring Boot并没有与Servlet容器的生命周期挂钩,而是使用Spring配置来引导自身和嵌入的Servlet容器。 过滤器和Servlet声明在Spring配置中被检测并注册到Servlet容器中。 有关更多详细信息,请参阅Spring Boot 文档

1.1.1. Context Hierarchy

DispatcherServlet expects a WebApplicationContext (an extension of a plain ApplicationContext) for its own configuration. WebApplicationContext has a link to the ServletContext and the Servlet with which it is associated. It is also bound to the ServletContext such that applications can use static methods on RequestContextUtils to look up the WebApplicationContext if they need access to it.

DispatcherServlet需要WebApplicationContext(一个ApplicationContext的扩展)用于其自身 配置。 WebApplicationContext包含指向ServletContext和与其关联的Servlet的链接。 它也绑定到ServletContext,以便应用程序可以在RequestContextUtils上使用静态方法来查找WebApplicationContext(如果需要访问它们)。

For many applications, having a single WebApplicationContext is simple and suffices. It is also possible to have a context hierarchy where one root WebApplicationContext is shared across multiple DispatcherServlet (or other Servlet) instances, each with its own child WebApplicationContext configuration. See Additional Capabilities of the ApplicationContext for more on the context hierarchy feature.

对于许多应用来说,拥有一个WebApplicationContext就足够了,并且很简单。也可以有一个上下文层次结构,其中一个根WebApplicationContext在多个DispatcherServlet(或其他Servlet)实例中共享,每个实例都有自己的子WebApplicationContext配置。有关上下文层次结构功能的详细信息,请参阅ApplicationContext的其他功能

The root WebApplicationContext typically contains infrastructure beans, such as data repositories and business services that need to be shared across multiple Servlet instances. Those beans are effectively inherited and can be overridden (that is, re-declared) in the Servlet-specific child WebApplicationContext, which typically contains beans local to the given Servlet. The following image shows this relationship:

根WebApplicationContext通常包含基础结构bean,例如需要在多个Servlet实例之间共享的数据存储库和业务服务。 这些Bean被有效地继承,并且可以在特定于Servlet的子WebApplicationContext中重写(即重新声明),该子WebApplicationContext通常包含给定Servlet本地的Bean。 下图显示了这种关系:

mvc context hierarchy

The following example configures a WebApplicationContext hierarchy:

以下示例配置WebApplicationContext层次结构:

Java

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { App1Config.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/app1/*" };
    }
}
 

If an application context hierarchy is not required, applications can return all configuration through getRootConfigClasses() and null from getServletConfigClasses().

 

如果不需要应用上下文层次结构,则应用程序可以通过getRootConfigClasses()返回所有配置,并从getServletConfigClasses()返回null。

The following example shows the web.xml equivalent:

以下示例展示了等效的web.xml:

<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/app1-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app1</servlet-name>
        <url-pattern>/app1/*</url-pattern>
    </servlet-mapping>

</web-app>
 

If an application context hierarchy is not required, applications may configure a “root” context only and leave the contextConfigLocation Servlet parameter empty.

 

如果应用不需要上下文层次结构,则应用程序可以仅配置“根”上下文,并将contextConfigLocation Servlet参数保留为空。

1.1.2. Special Bean Types

WebFlux

The DispatcherServlet delegates to special beans to process requests and render the appropriate responses. By “special beans” we mean Spring-managed Object instances that implement framework contracts. Those usually come with built-in contracts, but you can customize their properties and extend or replace them.

DispatcherServlet委托给特殊的bean处理请求并呈现适当的响应。 所谓的‘特殊bean’是指实现框架协议的Spring管理的对象实例。 这些通常带有内置协议,但是您可以自定义其属性并扩展或替换它们。

The following table lists the special beans detected by the DispatcherServlet:

下表列出了DispatcherServlet检测的特殊bean:

Bean typeExplanation

HandlerMapping

Map a request to a handler along with a list of interceptors for pre- and post-processing. The mapping is based on some criteria, the details of which vary by HandlerMapping implementation.

The two main HandlerMapping implementations are RequestMappingHandlerMapping (which supports @RequestMapping annotated methods) and SimpleUrlHandlerMapping (which maintains explicit registrations of URI path patterns to handlers).

将request与interceptors 列表一起映射到handler,以进行前置处理和后置处理。 映射基于某些条件,其细节因HandlerMapping实现而异。

HandlerMapping的两个主要实现是RequestMappingHandlerMapping(支持@RequestMapping注解方法)和SimpleUrlHandlerMapping(维护对handler的URI路径模式的显式注册)。

HandlerAdapter

Help the DispatcherServlet to invoke a handler mapped to a request, regardless of how the handler is actually invoked. For example, invoking an annotated controller requires resolving annotations. The main purpose of a HandlerAdapter is to shield the DispatcherServlet from such details.

 

帮助DispatcherServlet调用映射到请求的处理程序,无论实际如何调用该处理程序。 例如,调用带注解的控制器需要解析注解。 HandlerAdapter的主要目的是使DispatcherServlet免受此类细节的影响。

HandlerExceptionResolver

Strategy to resolve exceptions, possibly mapping them to handlers, to HTML error views, or other targets. See Exceptions.

 

解决异常的策略,可能将它们映射到处理程序,HTML错误视图或其他目标。

详情请参阅Exceptions

ViewResolver

Resolve logical String-based view names returned from a handler to an actual View with which to render to the response. See View Resolution and View Technologies.

 

将从handler返回的基于逻辑字符串的View解析为要用其呈现到响应的实际视图。

详情请参阅View ResolutionView Technologies

LocaleResolverLocaleContextResolver

Resolve the Locale a client is using and possibly their time zone, in order to be able to offer internationalized views. See Locale.

 

解析客户端正在使用的区域设置(可能还有它们的时区),以便能够提供国际化视图。

详情请参阅Locale

ThemeResolver

Resolve themes your web application can use — for example, to offer personalized layouts. See Themes.

 

解决Web应用程序可以使用的主题,例如,以提供个性化的布局。

详情请参阅Themes

MultipartResolver

Abstraction for parsing a multi-part request (for example, browser form file upload) with the help of some multipart parsing library. See Multipart Resolver.

 

借助一些multi-part解析库来解析multipart请求的抽象类(例如,浏览器表单文件上传)。

详情请参阅Multipart Resolver

FlashMapManager

Store and retrieve the “input” and the “output” FlashMap that can be used to pass attributes from one request to another, usually across a redirect. See Flash Attributes.

 

存储和检索“输入”和“输出”FlashMap,FlashMap可用于将属性从一个请求传递到另一个请求,一般是重定向。请参见Flash Attributes

1.1.3. Web MVC Config

WebFlux

Applications can declare the infrastructure beans listed in Special Bean Types that are required to process requests. The DispatcherServlet checks the WebApplicationContext for each special bean. If there are no matching bean types, it falls back on the default types listed in DispatcherServlet.properties.

应用程序可以声明处理请求所需的在‘特殊Bean类型’中列出的基础结构Bean。 DispatcherServlet检查每个特殊bean的WebApplicationContext。 如果没有匹配的bean类型,它将使用DispatcherServlet.properties中列出的默认类型。

In most cases, the MVC Config is the best starting point. It declares the required beans in either Java or XML and provides a higher-level configuration callback API to customize it.

多数情况下,MVC Config是最好的起点。 它使用Java或XML声明所需的bean,并提供更高级别的配置回调API对其进行自定义。

 

Spring Boot relies on the MVC Java configuration to configure Spring MVC and provides many extra convenient options.

 

Spring Boot依赖于MVC Java配置来配置Spring MVC,并提供了许多额外的方便选项。

1.1.4. Servlet Config

In a Servlet 3.0+ environment, you have the option of configuring the Servlet container programmatically as an alternative or in combination with a web.xml file. The following example registers a DispatcherServlet:

在Servlet 3.0+环境中,您可以选择以编程方式配置Servlet容器作为替代方案或与web.xml文件结合使用。 以下展示注册一个DispatcherServlet:

Java

import org.springframework.web.WebApplicationInitializer;

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
}

WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container. An abstract base class implementation of WebApplicationInitializer named AbstractDispatcherServletInitializer makes it even easier to register the DispatcherServlet by overriding methods to specify the servlet mapping and the location of the DispatcherServlet configuration.

WebApplicationInitializer是Spring MVC提供的接口,可确保检测到您的实现并将其自动用于初始化任何Servlet 3容器。
WebApplicationInitializer的抽象基类实现名为AbstractDispatcherServletInitializer,通过重写指定Servlet映射和DispatcherServlet配置位置的方法,使注册DispatcherServlet更容易。

This is recommended for applications that use Java-based Spring configuration, as the following example shows:

对于使用基于Java的Spring配置的应用程序,建议这样做,如以下示例所示:

Java

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { MyWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

If you use XML-based Spring configuration, you should extend directly from AbstractDispatcherServletInitializer, as the following example shows:

如果使用基于XML的Spring配置,则应直接继承AbstractDispatcherServletInitializer,如下示例所示:

Java

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext cxt = new XmlWebApplicationContext();
        cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        return cxt;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

AbstractDispatcherServletInitializer also provides a convenient way to add Filter instances and have them be automatically mapped to the DispatcherServlet, as the following example shows:

AbstractDispatcherServletInitializer还提供了一种方便的方法来添加Filter实例并使它们自动映射到DispatcherServlet,如以下示例所示:

Java

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    // ...

    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] {
            new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
    }
}

Each filter is added with a default name based on its concrete type and automatically mapped to the DispatcherServlet.

每个过滤器都会根据其具体类型添加一个默认名称,并自动映射到DispatcherServlet。

The isAsyncSupported protected method of AbstractDispatcherServletInitializer provides a single place to enable async support on the DispatcherServlet and all filters mapped to it. By default, this flag is set to true.

AbstractDispatcherServletInitializer的isAsyncSupported受保护方法提供了一个位置,以在DispatcherServlet及其映射的所有过滤器上启用异步支持。 默认情况下,此标志设置为true。

Finally, if you need to further customize the DispatcherServlet itself, you can override the createDispatcherServlet method.

最后,如果您需要自己进一步自定义DispatcherServlet,则可以重写createDispatcherServlet方法。

 

1.1.5. Processing

WebFlux

The DispatcherServlet processes requests as follows:

DispatcherServlet处理请求的方法如下:

  • The WebApplicationContext is searched for and bound in the request as an attribute that the controller and other elements in the process can use. It is bound by default under the DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE key.

  • 在请求中搜索WebApplicationContext并将其绑定为controller 和流程中其他元素可以使用的属性。 默认情况下,它是在DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE键下绑定的。

  • The locale resolver is bound to the request to let elements in the process resolve the locale to use when processing the request (rendering the view, preparing data, and so on). If you do not need locale resolving, you do not need the locale resolver.

  • 语言环境解析器绑定到请求,以使流程中的元素解析在处理请求(呈现视图,准备数据等)时要使用的语言环境。 如果不需要语言环境解析,则不需要语言环境解析器。

  • The theme resolver is bound to the request to let elements such as views determine which theme to use. If you do not use themes, you can ignore it.

  • 主题解析器绑定到请求,以使诸如视图之类的元素确定要使用的主题。 如果不使用主题,则可以将其忽略。

  • If you specify a multipart file resolver, the request is inspected for multiparts. If multiparts are found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process. See Multipart Resolver for further information about multipart handling.

  • 如果指定multipart 文件解析器,则将检查请求中是否有multipart 。 如果找到了multipart ,则将请求包装在MultipartHttpServletRequest中,以供流程中的其他元素进一步处理。 有关multipart处理的更多信息,请参见Multipart Resolver

  • An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering. Alternatively, for annotated controllers, the response can be rendered (within the HandlerAdapter) instead of returning a view.

  • 搜索适当的handler 。 如果找到handler ,则执行与handler (前置处理器,后置处理器和controller)关联的执行链,以准备模型或渲染。 另外,对于带注解的controller,可以呈现响应(在HandlerAdapter中)而不是返回视图。

  • If a model is returned, the view is rendered. If no model is returned (maybe due to a preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is rendered, because the request could already have been fulfilled.

  • 如果返回model ,则会呈现view 。如果没有返回model (可能是由于前置处理器或后置处理器拦截请求,可能是出于安全原因),则不会呈现view ,因为请求可能已经完成。

The HandlerExceptionResolver beans declared in the WebApplicationContext are used to resolve exceptions thrown during request processing. Those exception resolvers allow customizing the logic to address exceptions. See Exceptions for more details.

在WebApplicationContext中声明的HandlerExceptionResolver bean用于解决在请求处理期间引发的异常。 这些异常解析器允许定制逻辑以解决异常。 有关更多详细信息,请参见Exceptions 。

The Spring DispatcherServlet also supports the return of the last-modification-date, as specified by the Servlet API. The process of determining the last modification date for a specific request is straightforward: The DispatcherServlet looks up an appropriate handler mapping and tests whether the handler that is found implements the LastModified interface. If so, the value of the long getLastModified(request) method of the LastModified interface is returned to the client.

Spring DispatcherServlet还支持返回由Servlet API指定的最后修改日期。确定特定请求的最后修改日期的过程很简单:DispatcherServlet查找适当的处理程序映射,并测试找到的处理程序是否实现了LastModified接口。如果是,则将LastModified接口的long getLastModified(request)方法的值返回给客户端。

You can customize individual DispatcherServlet instances by adding Servlet initialization parameters (init-param elements) to the Servlet declaration in the web.xml file. The following table lists the supported parameters:

通过向web.xml文件中的Servlet声明添加Servlet初始化参数(init-param元素),可以自定义各个DispatcherServlet实例。下表列出了支持的参数:

Table 1. DispatcherServlet initialization parameters

DispatcherServlet 初始化参数列表

Parameter Explanation

contextClass

Class that implements ConfigurableWebApplicationContext, to be instantiated and locally configured by this Servlet. By default, XmlWebApplicationContext is used.

实现ConfigurableWebApplicationContext的类,将由此Servlet实例化和本地配置。 默认情况下,使用XmlWebApplicationContext。

contextConfigLocation

String that is passed to the context instance (specified by contextClass) to indicate where contexts can be found. The string consists potentially of multiple strings (using a comma as a delimiter) to support multiple contexts. In the case of multiple context locations with beans that are defined twice, the latest location takes precedence.

传递给上下文实例的字符串(由contextClass指定)以指示可以在哪里找到上下文。 该字符串可能包含多个字符串(使用逗号作为分隔符)以支持多个上下文。 对于具有两次定义的bean的多个上下文位置,以最新位置为准。

namespace

Namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet.

WebApplicationContext的命名空间。 默认为[servlet-name]-servlet。

throwExceptionIfNoHandlerFound

Whether to throw a NoHandlerFoundException when no handler was found for a request. The exception can then be caught with a HandlerExceptionResolver (for example, by using an @ExceptionHandler controller method) and handled as any others.

 

在找不到请求的处理程序时是否抛出NoHandlerFoundException。 然后可以使用HandlerExceptionResolver捕获异常(例如,通过使用@ExceptionHandler的controller方法)并与其他任何异常一样处理。

 

By default, this is set to false, in which case the DispatcherServlet sets the response status to 404 (NOT_FOUND) without raising an exception.

 

默认情况下,设置为false,在这种情况下,DispatcherServlet将响应状态设置为404(NOT_FOUND),而不会引发异常。

 

Note that, if default servlet handling is also configured, unresolved requests are always forwarded to the default servlet and a 404 is never raised.

 

注意,如果还配置了默认的servlet处理,那么未解析的请求总是被转发到默认的servlet,并且永远不会引发404。

1.1.6. Interception

All HandlerMapping implementations support handler interceptors that are useful when you want to apply specific functionality to certain requests — for example, checking for a principal. Interceptors must implement HandlerInterceptor from the org.springframework.web.servlet package with three methods that should provide enough flexibility to do all kinds of pre-processing and post-processing:

所有的HandlerMapping实现都支持处理程序拦截器,当您要将特定功能应用于某些请求时(例如,检查主体),该拦截器很有用。 拦截器必须使用三种方法从org.springframework.web.servlet包中实现HandlerInterceptor,这三种方法应提供足够的灵活性来执行各种前置处理和后置处理:

  • preHandle(..): Before the actual handler is executed

  • 在执行实际处理程序之前

  • postHandle(..): After the handler is executed

  • 处理程序执行后

  • afterCompletion(..): After the complete request has finished

  • 在完成请求之后

The preHandle(..) method returns a boolean value. You can use this method to break or continue the processing of the execution chain. When this method returns true, the handler execution chain continues. When it returns false, the DispatcherServlet assumes the interceptor itself has taken care of requests (and, for example, rendered an appropriate view) and does not continue executing the other interceptors and the actual handler in the execution chain.

preHandle(..)方法返回一个布尔值。 您可以使用此方法来中断或继续执行链的处理。 当此方法返回true时,处理程序执行链将继续。 当它返回false时,DispatcherServlet假定拦截器本身已经处理了请求(例如,渲染了一个适当的视图),并且不会继续执行其他拦截器和执行链中的实际处理程序。

See Interceptors in the section on MVC configuration for examples of how to configure interceptors. You can also register them directly by using setters on individual HandlerMapping implementations.

有关如何配置拦截器的示例,请参阅MVC配置部分中的Interceptors 。 您还可以通过使用各个HandlerMapping实现上的设置器直接注册它们。

Note that postHandle is less useful with @ResponseBody and ResponseEntity methods for which the response is written and committed within the HandlerAdapter and before postHandle. That means it is too late to make any changes to the response, such as adding an extra header. For such scenarios, you can implement ResponseBodyAdvice and either declare it as an Controller Advice bean or configure it directly on RequestMappingHandlerAdapter.

请注意,对于@ResponseBody和ResponseEntity方法而言,postHandle的用处不大,在HandlerAdapter中和postHandle之前写入并提交响应的@ResponseBody和ResponseEntity方法。 这意味着对响应进行任何更改为时已晚,例如添加额外的消息头。 对于此类情况,您可以实现ResponseBodyAdvice并将其声明为Controller Advice bean或直接在RequestMappingHandlerAdapter上进行配置。

 

1.1.7. Exceptions

WebFlux

If an exception occurs during request mapping or is thrown from a request handler (such as a @Controller), the DispatcherServlet delegates to a chain of HandlerExceptionResolver beans to resolve the exception and provide alternative handling, which is typically an error response.

如果在请求映射期间发生异常或从请求handler(如@Controller)抛出异常,DispatcherServlet将委托给HandlerExceptionResolver bean链以解决异常并提供替代处理,这通常是错误响应。

The following table lists the available HandlerExceptionResolver implementations:

下表列出了可用的HandlerExceptionResolver实现:

Table 2. HandlerExceptionResolver implementations
HandlerExceptionResolverDescription

SimpleMappingExceptionResolver

A mapping between exception class names and error view names. Useful for rendering error pages in a browser application.

 

异常类名和错误视图名之间的映射。用于在浏览器应用程序中呈现错误页。

DefaultHandlerExceptionResolver

Resolves exceptions raised by Spring MVC and maps them to HTTP status codes. See also alternative ResponseEntityExceptionHandler and REST API exceptions.

 

解析Spring MVC引发的异常并将其映射到HTTP状态代码。另请参见备用ResponseEntityExceptionHandler和REST API exceptions

ResponseStatusExceptionResolver

Resolves exceptions with the @ResponseStatus annotation and maps them to HTTP status codes based on the value in the annotation.

 

解决@ResponseStatus注解异常,并根据注解中的值将其映射到HTTP状态代码。

ExceptionHandlerExceptionResolver

Resolves exceptions by invoking an @ExceptionHandler method in a @Controller or a @ControllerAdvice class. See @ExceptionHandler methods.

 

通过在@Controller或@ControllerAdvice类中调用@ExceptionHandler方法来解决异常。 参见@ExceptionHandler methods

Chain of Resolvers

解析器链

You can form an exception resolver chain by declaring multiple HandlerExceptionResolver beans in your Spring configuration and setting their order properties as needed. The higher the order property, the later the exception resolver is positioned.

通过在Spring配置中声明多个HandlerExceptionResolver bean并根据需要设置它们的order属性,可以形成异常解析器链。order属性越高,异常解决程序的位置就越靠后。

The contract of HandlerExceptionResolver specifies that it can return:

HandlerExceptionResolver的协定指定它可以返回:

  • ModelAndView that points to an error view.

  • 指向错误视图的ModelAndView。

  • An empty ModelAndView if the exception was handled within the resolver.

  • 如果异常是在解析器中处理的,则为空的ModelAndView。

  • null if the exception remains unresolved, for subsequent resolvers to try, and, if the exception remains at the end, it is allowed to bubble up to the Servlet container.

  • 如果异常仍然未解决,则为空,以便后续的解析器尝试,如果异常仍然在末尾,则允许冒泡到Servlet容器。

The MVC Config automatically declares built-in resolvers for default Spring MVC exceptions, for @ResponseStatus annotated exceptions, and for support of @ExceptionHandler methods. You can customize that list or replace it.

MVC Config会自动为默认Spring MVC异常、@ResponseStatus注解的异常以及@ExceptionHandler方法的支持声明内置的解析器。您可以自定义或替换该列表。

Container Error Page

容器错误页面

If an exception remains unresolved by any HandlerExceptionResolver and is, therefore, left to propagate or if the response status is set to an error status (that is, 4xx, 5xx), Servlet containers can render a default error page in HTML. To customize the default error page of the container, you can declare an error page mapping in web.xml. The following example shows how to do so:

如果任何HandlerExceptionResolver都无法解决异常并因此将其传播或将响应状态设置为错误状态(即4xx,5xx),则Servlet容器可以在HTML中呈现默认错误页面。 要自定义容器的默认错误页面,您可以在web.xml中声明错误页面映射。 以下示例显示了如何执行此操作:

<error-page>
    <location>/error</location>
</error-page>

Given the preceding example, when an exception bubbles up or the response has an error status, the Servlet container makes an ERROR dispatch within the container to the configured URL (for example, /error). This is then processed by the DispatcherServlet, possibly mapping it to a @Controller, which could be implemented to return an error view name with a model or to render a JSON response, as the following example shows:

在前面的示例中,当出现异常或响应具有错误状态时,Servlet容器在容器内对配置的URL进行错误分派(例如/error)。然后由DispatcherServlet进行处理,可能将其映射到@Controller,后者可以实现为返回带有模型的错误视图名称或呈现JSON响应,如下例所示:

Java

@RestController
public class ErrorController {

    @RequestMapping(path = "/error")
    public Map<String, Object> handle(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", request.getAttribute("javax.servlet.error.status_code"));
        map.put("reason", request.getAttribute("javax.servlet.error.message"));
        return map;
    }
}
 

The Servlet API does not provide a way to create error page mappings in Java. You can, however, use both a WebApplicationInitializer and a minimal web.xml.

Servlet API没有提供在Java中创建错误页面映射的方法。 但是,您可以同时使用WebApplicationInitializer和最小的web.xml。

1.1.8. View Resolution

WebFlux

Spring MVC defines the ViewResolver and View interfaces that let you render models in a browser without tying you to a specific view technology. ViewResolver provides a mapping between view names and actual views. View addresses the preparation of data before handing over to a specific view technology.

Spring MVC定义了ViewResolver和View接口,这些接口使您可以在浏览器中呈现模型,而无需将您与特定的视图技术联系在一起。 ViewResolver提供视图名称和实际视图之间的映射。 View致力于在移交给特定的View技术之前准备数据。

The following table provides more details on the ViewResolver hierarchy:

下表提供了有关ViewResolver层次结构的更多详细信息:

Table 3. ViewResolver implementations
ViewResolverDescription

AbstractCachingViewResolver

Sub-classes of AbstractCachingViewResolver cache view instances that they resolve. Caching improves performance of certain view technologies. You can turn off the cache by setting the cache property to false. Furthermore, if you must refresh a certain view at runtime (for example, when a FreeMarker template is modified), you can use the removeFromCache(String viewName, Locale loc) method.

 

AbstractCachingViewResolver的子类缓存它们解析的视图实例。 缓存可以提高某些视图技术的性能。 您可以通过将缓存属性设置为false来关闭缓存。 此外,如果必须在运行时刷新某个视图(例如,当修改FreeMarker模板时),则可以使用removeRemoveFromCache(String viewName,Locale loc)方法。

XmlViewResolver

Implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring’s XML bean factories. The default configuration file is /WEB-INF/views.xml.

 

viewsolver的实现,它接受使用与Spring的XML bean工厂相同的DTD编写的XML配置文件。默认配置文件是/WEB-INF/views.xml。

ResourceBundleViewResolver

Implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle base name. For each view it is supposed to resolve, it uses the value of the property [viewname].(class) as the view class and the value of the property [viewname].url as the view URL. You can find examples in the chapter on View Technologies.

 

viewsolver的实现,它在由bundle基名称指定的ResourceBundle中使用bean定义。对于要解析的每个视图,它使用属性[viewname].class的值作为视图类,使用属性[viewname].url的值作为视图url。您可以在View Technologies的章节中找到示例。

UrlBasedViewResolver

Simple implementation of the ViewResolver interface that affects the direct resolution of logical view names to URLs without an explicit mapping definition. This is appropriate if your logical names match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.

 

viewsolver接口的简单实现,它影响逻辑视图名称到url的直接解析,而无需显式映射定义。如果逻辑名称以简单的方式与视图资源的名称匹配,而不需要任意映射,这是合理的。

InternalResourceViewResolver

Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views generated by this resolver by using setViewClass(..). See the UrlBasedViewResolver javadoc for details.

 

UrlBasedViewResolver的子类,它支持InternalResourceView(实际上是Servlet和JSP)以及JstlView和TilesView等子类。 您可以使用setViewClass(..)为该解析器生成的所有视图指定视图类。 有关详细信息,请参见UrlBasedViewResolver javadoc。

FreeMarkerViewResolver

Convenient subclass of UrlBasedViewResolver that supports FreeMarkerView and custom subclasses of them.

 

UrlBasedViewResolver的子类,支持FreeMarkerView和它们的自定义子类。

ContentNegotiatingViewResolver

Implementation of the ViewResolver interface that resolves a view based on the request file name or Accept header. See Content Negotiation.

基于请求文件名或Accept消息头解析视图的ViewResolver接口的实现。详情见Content Negotiation

Handling

WebFlux

You can chain view resolvers by declaring more than one resolver bean and, if necessary, by setting the order property to specify ordering. Remember, the higher the order property, the later the view resolver is positioned in the chain.

您可以通过声明多个解析器bean来链接视图解析器,并在必要时通过设置order属性来指定排序。 请记住,order属性越高,视图解析器在链中的定位就越晚。

The contract of a ViewResolver specifies that it can return null to indicate that the view could not be found. However, in the case of JSPs and InternalResourceViewResolver, the only way to figure out if a JSP exists is to perform a dispatch through RequestDispatcher. Therefore, you must always configure an InternalResourceViewResolver to be last in the overall order of view resolvers.

Configuring view resolution is as simple as adding ViewResolver beans to your Spring configuration. The MVC Config provides a dedicated configuration API for View Resolvers and for adding logic-less View Controllers which are useful for HTML template rendering without controller logic.

Redirecting

WebFlux

The special redirect: prefix in a view name lets you perform a redirect. The UrlBasedViewResolver (and its subclasses) recognize this as an instruction that a redirect is needed. The rest of the view name is the redirect URL.

The net effect is the same as if the controller had returned a RedirectView, but now the controller itself can operate in terms of logical view names. A logical view name (such as redirect:/myapp/some/resource) redirects relative to the current Servlet context, while a name such as redirect:https://myhost.com/some/arbitrary/path redirects to an absolute URL.

Note that, if a controller method is annotated with the @ResponseStatus, the annotation value takes precedence over the response status set by RedirectView.

Forwarding

You can also use a special forward: prefix for view names that are ultimately resolved by UrlBasedViewResolver and subclasses. This creates an InternalResourceView, which does a RequestDispatcher.forward(). Therefore, this prefix is not useful with InternalResourceViewResolver and InternalResourceView (for JSPs), but it can be helpful if you use another view technology but still want to force a forward of a resource to be handled by the Servlet/JSP engine. Note that you may also chain multiple view resolvers, instead.

Content Negotiation

WebFlux

ContentNegotiatingViewResolver does not resolve views itself but rather delegates to other view resolvers and selects the view that resembles the representation requested by the client. The representation can be determined from the Accept header or from a query parameter (for example, "/path?format=pdf").

The ContentNegotiatingViewResolver selects an appropriate View to handle the request by comparing the request media types with the media type (also known as Content-Type) supported by the View associated with each of its ViewResolvers. The first View in the list that has a compatible Content-Type returns the representation to the client. If a compatible view cannot be supplied by the ViewResolver chain, the list of views specified through the DefaultViews property is consulted. This latter option is appropriate for singleton Views that can render an appropriate representation of the current resource regardless of the logical view name. The Accept header can include wildcards (for example text/*), in which case a View whose Content-Type is text/xml is a compatible match.

See View Resolvers under MVC Config for configuration details.

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值