The MVC Java configuration and the MVC XML namespace provide default configuration suitable for most applications and a
configuration API to customize it.
MVC Java 配置和 MVC XML 命名空间提供了适用于大多数应用的默认配置以及一个用于自定义的配置 API。
For more advanced customizations, which are not available in the configuration API,
see Advanced Java Config and Advanced XML Config.
为了更高级的自定义设置,这些在配置 API 中不可用,请参阅高级 Java 配置和高级 XML 配置。
You do not need to understand the underlying beans created by the MVC Java configuration and the MVC namespace. If you
want to learn more, see Special Bean Types
and Web MVC Config.
您不需要理解由 MVC Java 配置和 MVC 命名空间创建的底层 bean。如果您想了解更多,请参阅特殊 Bean 类型和 Web MVC 配置。
1.11.1. 启用 MVC 配置
In Java configuration, you can use the @EnableWebMvc annotation to enable MVC configuration, as the following example
shows:
在 Java 配置中,您可以使用 @EnableWebMvc 注解来启用 MVC 配置,如下例所示:
In XML configuration, you can use the <mvc:annotation-driven> element to enable MVC configuration, as the following
example shows:
在 XML 配置中,您可以使用 <mvc:annotation-driven> 元素来启用 MVC 配置,如下例所示:
The preceding example registers a number of Spring MVC infrastructure beans and
adapts to dependencies available on the classpath (for example, payload converters for JSON, XML, and others).
前一个示例注册了多个 Spring MVC 基础设施 bean,并适应类路径上可用的依赖项(例如,用于 JSON、XML 等的数据包转换器)。
1.11.2. MVC 配置 API
In Java configuration, you can implement the WebMvcConfigurer interface, as the following example shows:
在 Java 配置中,您可以实现 WebMvcConfigurer 接口,如下例所示:
In XML, you can check attributes and sub-elements of <mvc:annotation-driven/>. You can view
the Spring MVC XML schema or use the code completion feature of your IDE
to discover what attributes and sub-elements are available.
在 XML 中,您可以检查 <mvc:annotation-driven/> 的属性和子元素。您可以通过查看 Spring MVC XML 模式或使用您 IDE
的代码补全功能来发现可用的属性和子元素。
By default, formatters for various number and date types are installed, along with support for customization via
@NumberFormat and @DateTimeFormat on fields.
默认情况下,已安装各种数字和日期类型的格式化程序,以及通过字段上的 @NumberFormat 和 @DateTimeFormat 进行自定义的支持。
To register custom formatters and converters in Java config, use the following:
在 Java 配置中注册自定义格式化和转换器,请使用以下方法:
To do the same in XML config, use the following:
在 XML 配置中执行相同操作,请使用以下内容:
By default Spring MVC considers the request Locale when parsing and formatting date values. This works for forms where
dates are represented as Strings with "input" form fields. For "date" and "time" form fields, however, browsers use a
fixed format defined in the HTML spec.
默认情况下,Spring MVC 在解析和格式化日期值时会考虑请求的区域设置。这对于日期以字符串形式表示为“input”表单字段的情况有效。然而,对于“日期”和“时间”表单字段,浏览器使用
HTML 规范中定义的固定格式。
For such cases date and time formatting can be customized as follows:
对于此类情况,日期和时间格式可以按以下方式自定义:
See the
FormatterRegistrar SPI
and the FormattingConversionServiceFactoryBean for more information on when to use FormatterRegistrar
implementations.
查看 FormatterRegistrar SPI 和 FormattingConversionServiceFactoryBean 以获取有关何时使用 FormatterRegistrar 实现的更多信息。
By default,
if Bean Validation
is present on the classpath (for example, Hibernate Validator), the LocalValidatorFactoryBean is registered as a
global Validator for use with
@Valid and Validated on controller method arguments.
默认情况下,如果类路径上存在 Bean Validation(例如 Hibernate Validator),则 LocalValidatorFactoryBean 被注册为全局
Validator,用于在控制器方法参数上与 @Valid 和 Validated 一起使用。
In Java configuration, you can customize the global Validator instance, as the following example shows:
在 Java 配置中,您可以自定义全局 Validator 实例,如下例所示:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
Note that you can also register Validator implementations locally, as the following example shows:
请注意,您还可以在本地注册 Validator 实现,如下例所示:
If you need to have a LocalValidatorFactoryBean injected somewhere, create a bean and mark it with @Primary in order
to avoid conflict with the one declared in the MVC configuration.
如果您需要在某处注入一个 LocalValidatorFactoryBean ,请创建一个 Bean 并用 @Primary 标记它,以避免与 MVC 配置中声明的那一个发生冲突。
In Java configuration, you can register interceptors to apply to incoming requests, as the following example shows:
在 Java 配置中,您可以注册拦截器以应用于传入的请求,如下例所示:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
Mapped interceptors are not ideally suited as a security layer due to the potential for a mismatch with annotated
controller path matching, which can also match trailing slashes and path extensions transparently, along with other path
matching options.
映射拦截器并不理想地适合作为安全层,因为它们可能与注解控制器路径匹配不匹配,这也可以透明地匹配尾随斜杠和路径扩展,以及其他路径匹配选项。
Many of these options have been deprecated but the potential for a mismatch remains. Generally, we recommend using
Spring Security which includes a
dedicated MvcRequestMatcher
to align with Spring MVC path matching and also has a security firewall that blocks many unwanted characters in URL
paths.
许多这些选项已被弃用,但潜在的不匹配风险仍然存在。通常,我们建议使用 Spring Security,它包括一个专门的 MvcRequestMatcher 以与
Spring MVC 路径匹配相一致,并且还有一个安全防火墙,可以阻止 URL 路径中的许多不受欢迎的字符。
You can configure how Spring MVC determines the requested media types from the request (for example, Accept header,
URL path extension, query parameter, and others).
您可以为 Spring MVC 配置如何从请求中确定请求的媒体类型(例如, Accept 头信息、URL 路径扩展名、查询参数等)。
By default, only the Accept header is checked.
默认情况下,只有 Accept 头被检查。
If you must use URL-based content type resolution, consider using the query parameter strategy over path extensions.
See Suffix Match and Suffix Match and RFD
for more details.
如果您必须使用基于 URL 的内容类型解析,请考虑使用查询参数策略而不是路径扩展。有关更多详细信息,请参阅后缀匹配和后缀匹配及
RFD。
In Java configuration, you can customize requested content type resolution, as the following example shows:
在 Java 配置中,您可以自定义请求内容类型的解析,如下例所示:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
1.11.7. 消息转换器
You can customize HttpMessageConverter in Java configuration by overriding
configureMessageConverters() (
to replace the default converters created by Spring MVC) or by overriding
extendMessageConverters() (
to customize the default converters or add additional converters to the default ones).
您可以通过覆盖 configureMessageConverters() (以替换由 Spring MVC 创建的默认转换器)或覆盖 extendMessageConverters()
(以自定义默认转换器或向默认转换器添加额外的转换器)来在 Java 配置中自定义 HttpMessageConverter 。
The following example adds XML and Jackson JSON converters with a customized ObjectMapper instead of the default
ones:
以下示例使用自定义的 ObjectMapper 代替默认的 XML 和 Jackson JSON 转换器:
In the preceding example,
Jackson2ObjectMapperBuilder
is used to create a common configuration for both MappingJackson2HttpMessageConverter and
MappingJackson2XmlHttpMessageConverter with indentation enabled, a customized date format, and the registration of
jackson-module-parameter-names, Which adds support for
accessing parameter names (a feature added in Java 8).
在前面示例中,使用 Jackson2ObjectMapperBuilder 为 MappingJackson2HttpMessageConverter 和
MappingJackson2XmlHttpMessageConverter 创建了一个共同的配置,启用了缩进,自定义了日期格式,并注册了
jackson-module-parameter-names ,这增加了访问参数名称(Java 8 中添加的功能)的支持。
This builder customizes Jackson’s default properties as follows:
此构建器如下定制 Jackson 的默认属性:
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
is disabled.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 已被禁用。
MapperFeature.DEFAULT_VIEW_INCLUSION
is disabled.MapperFeature.DEFAULT_VIEW_INCLUSION 已被禁用。
It also automatically registers the following well-known modules if they are detected on the classpath:
它还会自动注册以下在类路径上检测到的知名模块:
jackson-datatype-joda: Support for Joda-Time types.
jackson-datatype-joda:支持 Joda-Time 类型。
jackson-datatype-jsr310: Support for Java 8 Date and Time API
types.
jackson-datatype-jsr310:支持 Java 8 日期和时间 API 类型。
jackson-datatype-jdk8: Support for other Java 8 types, such as
Optional.
jackson-datatype-jdk8:支持其他 Java 8 类型,例如 Optional 。
jackson-module-kotlin: Support for Kotlin classes and data
classes.
jackson-module-kotlin : 支持 Kotlin 类和数据类。
Enabling indentation with Jackson XML support requires
woodstox-core-asl
dependency in addition to
jackson-dataformat-xml one.
启用 Jackson XML 支持下的缩进功能需要除了 jackson-dataformat-xml 之外,还需要 woodstox-core-asl 依赖。
Other interesting Jackson modules are available:
其他有趣的 Jackson 模块可供使用:
jackson-datatype-money: Support for javax.money types (
unofficial module).
jackson-datatype-money:支持 javax.money 类型(非官方模块)。
jackson-datatype-hibernate: Support for Hibernate-specific
types and properties (including lazy-loading aspects).
jackson-datatype-hibernate:支持 Hibernate 特定类型和属性(包括懒加载方面)。
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
1.11.8. 视图控制器
This is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked. You
can use it in static cases when there is no Java controller logic to run before the view generates the response.
这是一个在调用时立即转发到视图的 ParameterizableViewController 定义的快捷方式。您可以在没有 Java
控制器逻辑在生成响应之前运行的静态情况下使用它。
The following example of Java configuration forwards a request for / to a view called home:
以下 Java 配置示例将请求转发到名为 home 的视图:
The following example achieves the same thing as the preceding example, but with XML, by using the
<mvc:view-controller> element:
以下示例通过使用 <mvc:view-controller> 元素,以 XML 方式实现了与上一个示例相同的功能:
If an @RequestMapping method is mapped to a URL for any HTTP method then a view controller cannot be used to handle
the same URL.
如果一个 @RequestMapping 方法被映射到任何 HTTP 方法的 URL 上,则无法使用视图控制器来处理相同的 URL。
This is because a match by URL to an annotated controller is considered a strong enough indication of endpoint ownership
so that a 405 (METHOD_NOT_ALLOWED), a 415 (UNSUPPORTED_MEDIA_TYPE), or similar response can be sent to the client to
help with debugging.
这是因为通过 URL 匹配到注解控制器被视为足够强的端点所有权的指示,因此可以向客户端发送
405(METHOD_NOT_ALLOWED)、415(UNSUPPORTED_MEDIA_TYPE)或类似的响应,以帮助调试。
For this reason it is recommended to avoid splitting URL handling across an annotated controller and a view
controller.
因此,建议避免在注解控制器和视图控制器之间分割 URL 处理。
The MVC configuration simplifies the registration of view resolvers.
MVC 配置简化了视图解析器的注册。
The following Java configuration example configures content negotiation view resolution by using JSP and Jackson as a
default View for JSON rendering:
以下 Java 配置示例通过使用 JSP 和 Jackson 作为默认的 View 来配置内容协商视图解析,用于 JSON 渲染:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
Note, however, that FreeMarker, Tiles, Groovy Markup, and script templates also require configuration of the underlying
view technology.
请注意,然而,FreeMarker、Tiles、Groovy Markup 和脚本模板同样需要配置底层视图技术。
The MVC namespace provides dedicated elements. The following example works with FreeMarker:
MVC 命名空间提供了专用元素。以下示例使用 FreeMarker:
In Java configuration, you can add the respective Configurer bean, as the following example shows:
在 Java 配置中,您可以添加相应的 Configurer Bean,如下例所示:
1.11.10. 静态资源
This option provides a convenient way to serve static resources from a list of
Resource
-based locations.
此选项提供了一种方便的方式从基于 Resource 的列表位置中提供静态资源。
In the next example, given a request that starts with /resources, the relative path is used to find and serve static
resources relative to /public under the web application root or on the classpath under /static. The resources are
served with a one-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests
made by the browser. The Last-Modified information is deduced from Resource#lastModified so that HTTP conditional
requests are supported with "Last-Modified" headers.
在下一个示例中,给定一个以 /resources 开始的请求,使用相对路径在 Web 应用程序根目录或 /static 下的类路径中查找并服务相对于
/public 的静态资源。这些资源以一年的未来过期时间提供服务,以确保最大程度地使用浏览器缓存并减少浏览器发出的 HTTP 请求。
Last-Modified 信息从 Resource#lastModified 中推断出来,以便支持带有 "Last-Modified" 头的 HTTP 条件请求。
The following listing shows how to do so with Java configuration:
以下列表展示了如何使用 Java 配置来完成此操作:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
See also HTTP caching support for static resources.
参见对静态资源的 HTTP 缓存支持。
The resource handler also supports a chain of
ResourceResolver
implementations and
ResourceTransformer
implementations, which you can use to create a toolchain for working with optimized resources.
资源处理器还支持一系列 ResourceResolver 实现和 ResourceTransformer 实现,您可以使用它们来创建用于处理优化资源的工具链。
You can use the VersionResourceResolver for versioned resource URLs based on an MD5 hash computed from the content, a
fixed application version, or other. A ContentVersionStrategy (MD5 hash) is a good choice — with some notable
exceptions, such as JavaScript resources used with a module loader.
您可以使用基于内容、固定应用程序版本或其他内容的 MD5 哈希计算的 VersionResourceResolver 版本化资源 URL。
ContentVersionStrategy (MD5 哈希)是一个不错的选择——除了一些显著的例外,例如与模块加载器一起使用的 JavaScript 资源。
The following example shows how to use VersionResourceResolver in Java configuration:
以下示例展示了如何在 Java 配置中使用 VersionResourceResolver
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
You can then use ResourceUrlProvider to rewrite URLs and apply the full chain of resolvers and transformers — for
example, to insert versions. The MVC configuration provides a ResourceUrlProvider bean so that it can be injected into
others. You can also make the rewrite transparent with the ResourceUrlEncodingFilter for Thymeleaf, JSPs, FreeMarker,
and others with URL tags that rely on HttpServletResponse#encodeURL.
您可以使用 ResourceUrlProvider 来重写 URL 并应用完整的解析器和转换器链——例如,插入版本。MVC 配置提供了一个
ResourceUrlProvider 豆芽,以便它可以被注入到其他组件中。您还可以使用 ResourceUrlEncodingFilter 使重写对
Thymeleaf、JSP、FreeMarker 等透明,这些标签依赖于 HttpServletResponse#encodeURL 的 URL 标签。
Note that, when using both EncodedResourceResolver (for example, for serving gzipped or brotli-encoded resources) and
VersionResourceResolver, you must register them in this order. That ensures content-based versions are always computed
reliably, based on the unencoded file.
请注意,当同时使用 EncodedResourceResolver (例如,用于提供 gzip 或 brotli 编码的资源)和 VersionResourceResolver
时,您必须按此顺序注册它们。这确保了基于内容版本的始终可靠计算,基于未编码的文件。
For WebJars, versioned URLs like /webjars/jquery/1.2.0/jquery.min.js are the
recommended and most efficient way to use them. The related resource location is configured out of the box with Spring
Boot (or can be configured manually via ResourceHandlerRegistry) and does not require to add the
org.webjars:webjars-locator-core dependency.
对于 WebJars,使用版本化的 URL 如 /webjars/jquery/1.2.0/jquery.min.js 是推荐且最有效的方式。相关资源位置在 Spring Boot
中默认配置(或可以通过 ResourceHandlerRegistry 手动配置)且无需添加 org.webjars:webjars-locator-core 依赖。
Version-less URLs like /webjars/jquery/jquery.min.js are supported through the WebJarsResourceResolver which is
automatically registered when the org.webjars:webjars-locator-core library is present on the classpath, at the cost of
a classpath scanning that could slow down application startup. The resolver can re-write URLs to include the version of
the jar and can also match against incoming URLs without versions — for example, from /webjars/jquery/jquery.min.js to
/webjars/jquery/1.2.0/jquery.min.js.
无版本号的 URL,如 /webjars/jquery/jquery.min.js ,通过 WebJarsResourceResolver 支持,当
org.webjars:webjars-locator-core 库存在于类路径上时自动注册,但这会以类路径扫描可能减慢应用程序启动为代价。解析器可以将
URL 重写以包含 jar 的版本,并且也可以匹配不带版本的传入 URL——例如,从 /webjars/jquery/jquery.min.js 到
/webjars/jquery/1.2.0/jquery.min.js 。
The Java configuration based on ResourceHandlerRegistry provides further options for fine-grained control, e.g.
last-modified behavior and optimized resource resolution.
基于 ResourceHandlerRegistry 的 Java 配置提供了更进一步的选项,例如控制最后修改行为和优化资源解析。
1.11.11. 默认 Servlet
Spring MVC allows for mapping the DispatcherServlet to / (thus overriding the mapping of the container’s default
Servlet), while still allowing static resource requests to be handled by the container’s default Servlet. It configures
a DefaultServletHttpRequestHandler with a URL mapping of /** and the lowest priority relative to other URL
mappings.
Spring MVC 允许将 DispatcherServlet 映射到 / (从而覆盖容器默认 Servlet 的映射),同时仍然允许静态资源请求由容器的默认
Servlet 处理。它配置了一个 DefaultServletHttpRequestHandler ,其 URL 映射为 /** ,并且相对于其他 URL 映射具有最低优先级。
This handler forwards all requests to the default Servlet. Therefore, it must remain last in the order of all other URL
HandlerMappings. That is the case if you use <mvc:annotation-driven>. Alternatively, if you set up your own
customized HandlerMapping instance, be sure to set its order property to a value lower than that of the
DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.
此处理器将所有请求转发到默认 Servlet。因此,它必须排在所有其他 URL HandlerMappings 的最后。如果您使用
<mvc:annotation-driven> ,情况就是这样。或者,如果您设置了自定义的 HandlerMapping 实例,请确保将其 order 属性设置为低于
DefaultServletHttpRequestHandler 的值,即 Integer.MAX_VALUE 。
The following example shows how to enable the feature by using the default setup:
以下示例展示了如何通过默认设置启用该功能:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
The caveat to overriding the / Servlet mapping is that the RequestDispatcher for the default Servlet must be
retrieved by name rather than by path. The DefaultServletHttpRequestHandler tries to auto-detect the default Servlet
for the container at startup time, using a list of known names for most of the major Servlet containers (including
Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere).
覆盖 / Servlet 映射的注意事项是,必须通过名称而不是通过路径来检索 RequestDispatcher 默认 Servlet。
DefaultServletHttpRequestHandler 尝试在启动时自动检测容器中的默认 Servlet,使用大多数主要 Servlet 容器的已知名称列表(包括
Tomcat、Jetty、GlassFish、JBoss、Resin、WebLogic 和 WebSphere)。
If the default Servlet has been custom-configured with a different name, or if a different Servlet container is being
used where the default Servlet name is unknown, then you must explicitly provide the default Servlet’s name, as the
following example shows:
如果默认 Servlet 已被自定义配置为不同的名称,或者正在使用默认 Servlet 名称未知的不同 Servlet 容器,那么您必须明确提供默认
Servlet 的名称,如下例所示:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
You can customize options related to path matching and treatment of the URL. For details on the individual options, see
the
PathMatchConfigurer
javadoc.
您可以根据需要自定义与路径匹配和 URL 处理相关的选项。有关各个选项的详细信息,请参阅 PathMatchConfigurer javadoc。
The following example shows how to customize path matching in Java configuration:
以下示例展示了如何在 Java 配置中自定义路径匹配:
The following example shows how to achieve the same configuration in XML:
以下示例展示了如何在 XML 中实现相同的配置:
1.11.13. 高级 Java 配置
@EnableWebMvc imports DelegatingWebMvcConfiguration, which:
@EnableWebMvc 导入 DelegatingWebMvcConfiguration ,其中:
Provides default Spring configuration for Spring MVC applications
提供默认的 Spring 配置,适用于 Spring MVC 应用程序
Detects and delegates to WebMvcConfigurer implementations to customize that configuration.
检测并将配置定制委托给 WebMvcConfigurer 实现。
For advanced mode, you can remove @EnableWebMvc and extend directly from DelegatingWebMvcConfiguration instead of
implementing WebMvcConfigurer, as the following example shows:
对于高级模式,您可以直接从 DelegatingWebMvcConfiguration 扩展,而不是实现 WebMvcConfigurer ,如以下示例所示:
You can keep existing methods in WebConfig, but you can now also override bean declarations from the base class, and
you can still have any number of other WebMvcConfigurer implementations on the classpath.
您可以在 WebConfig 中保留现有方法,但现在您也可以覆盖基类中的 bean 声明,并且您仍然可以在类路径上有任意数量的其他
WebMvcConfigurer 实现。
1.11.14. 高级 XML 配置
The MVC namespace does not have an advanced mode. If you need to customize a property on a bean that you cannot change
otherwise, you can use the BeanPostProcessor lifecycle hook of the Spring ApplicationContext, as the following
example shows:
MVC 命名空间没有高级模式。如果您需要自定义一个无法更改的 bean 属性,可以使用 Spring 的 ApplicationContext 的
BeanPostProcessor 生命周期钩子,如下例所示:
Note that you need to declare MyPostProcessor as a bean, either explicitly in XML or by letting it be detected through
a <component-scan/> declaration.
请注意,您需要将 MyPostProcessor 声明为一个 bean,可以是显式地在 XML 中声明,或者通过 <component-scan/> 声明让它被检测到。