Spring MVC
Spring Boot 有许多包括 Spring MVC 的启动器。请注意,某些启动器包含对 Spring MVC 的依赖项,而不是直接包含它。本部分回答有关 Spring MVC 和 Spring Boot 的常见问题。
Spring Boot has a number of starters that include Spring MVC. Note that some starters include a dependency on Spring MVC rather than include it directly. This section answers common questions about Spring MVC and Spring Boot.
Write a JSON REST Service
只要类路径上存在 Jackson2,Spring Boot 应用程序中的任何 Spring @RestController
都应默认呈现 JSON 响应,如下例所示:
Any Spring @RestController
in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:
只要 MyThing
可以由 Jackson2 序列化(对于普通 POJO 或 Groovy 对象为 true),http://localhost:8080/thing
默认提供其 JSON 表示。请注意,在浏览器中,您有时可能会看到 XML 响应,因为浏览器往往会发送首选 XML 的接受标头。
As long as MyThing
can be serialized by Jackson2 (true for a normal POJO or Groovy object), then http://localhost:8080/thing
serves a JSON representation of it by default.
Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.
Write an XML REST Service
如果您在类路径上拥有 Jackson XML 扩展(jackson-dataformat-xml
),则可以使用它来呈现 XML 响应。我们用于 JSON 的先前示例将起作用。要使用 Jackson XML 呈现器,请将以下依赖项添加到您的项目:
If you have the Jackson XML extension (jackson-dataformat-xml
) on the classpath, you can use it to render XML responses.
The previous example that we used for JSON would work.
To use the Jackson XML renderer, add the following dependency to your project:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
如果没有 Jackson 的 XML 扩展,并且有 JAXB,则可以通过添加对被注释为 @XmlRootElement
的 MyThing
的额外要求,呈现 XML,如下例所示:
If Jackson’s XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having MyThing
annotated as @XmlRootElement
, as shown in the following example:
您需要确保 JAXB 库是您项目的一部分,例如通过添加:
You will need to ensure that the JAXB library is part of your project, for example by adding:
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
要让服务器呈现 XML 而不是 JSON,您可能需要发送 |
To get the server to render XML instead of JSON, you might have to send an |
Customize the Jackson ObjectMapper
Spring MVC(客户端和服务器端)使用 HttpMessageConverters
在 HTTP 交换中协商内容转换。如果您在类路径上有 Jackson,那么您已经获得了由 Jackson2ObjectMapperBuilder
提供的默认转换器(实例已为您自动配置)。
Spring MVC (client and server side) uses HttpMessageConverters
to negotiate content conversion in an HTTP exchange.
If Jackson is on the classpath, you already get the default converter(s) provided by Jackson2ObjectMapperBuilder
, an instance of which is auto-configured for you.
ObjectMapper
(或 Jackson XML 转换器的 XmlMapper
)实例(默认创建)具有以下自定义属性:
The ObjectMapper
(or XmlMapper
for Jackson XML converter) instance (created by default) has the following customized properties:
-
MapperFeature.DEFAULT_VIEW_INCLUSION
is disabled -
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
is disabled -
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
is disabled -
SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS
is disabled
Spring Boot 还具有一些功能,可以更轻松地自定义此行为。
Spring Boot also has some features to make it easier to customize this behavior.
您可以使用环境配置 ObjectMapper
和 XmlMapper
实例。Jackson 提供了一套丰富的开关功能,可用于配置其处理的各个方面。这些功能在多个枚举(在 Jackson 中)中进行了描述,该枚举映射到环境中的属性:
You can configure the ObjectMapper
and XmlMapper
instances by using the environment.
Jackson provides an extensive suite of on/off features that can be used to configure various aspects of its processing.
These features are described in several enums (in Jackson) that map onto properties in the environment:
Enum | Property | Values |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
configprop:spring.jackson.default-property-inclusion[] |
|
例如,若要启用 pretty print,请设置`spring.jackson.serialization.indent_output=true`。请注意,由于使用了relaxed binding,indent_output`的大小写不必匹配相应枚举常数的大小写,即`INDENT_OUTPUT
。
For example, to enable pretty print, set spring.jackson.serialization.indent_output=true
.
Note that, thanks to the use of relaxed binding, the case of indent_output
does not have to match the case of the corresponding enum constant, which is INDENT_OUTPUT
.
这种基于环境的配置应用于自动配置的`Jackson2ObjectMapperBuilder`Bean,并应用于使用builder创建的任何映射器,包括自动配置的`ObjectMapper`Bean。
This environment-based configuration is applied to the auto-configured Jackson2ObjectMapperBuilder
bean and applies to any mappers created by using the builder, including the auto-configured ObjectMapper
bean.
上下文的`Jackson2ObjectMapperBuilder`可以通过一个或多个`Jackson2ObjectMapperBuilderCustomizer`Beans进行定制。此类定制器Beans可以排序(Boot自己的定制器有0的序数),从而允许在Boot定制之前和之后都应用额外的定制。
The context’s Jackson2ObjectMapperBuilder
can be customized by one or more Jackson2ObjectMapperBuilderCustomizer
beans.
Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.
任何`com.fasterxml.jackson.databind.Module`类型的Bean都会自动注册到自动配置的`Jackson2ObjectMapperBuilder`中,并应用于它创建的任何`ObjectMapper`实例。当您向应用程序中添加新功能时,这种方式提供了一种全局机制,以贡献定制模块。
Any beans of type com.fasterxml.jackson.databind.Module
are automatically registered with the auto-configured Jackson2ObjectMapperBuilder
and are applied to any ObjectMapper
instances that it creates.
This provides a global mechanism for contributing custom modules when you add new features to your application.
如果您想完全替换默认的`ObjectMapper`,请为该类型定义一个`@Bean`并将其标记为`@Primary`,或者,如果您更喜欢基于builder的方法,请定义一个`Jackson2ObjectMapperBuilder``@Bean`。请注意,在任何一种情况下,此操作都会禁用`ObjectMapper`的所有自动配置。
If you want to replace the default ObjectMapper
completely, either define a @Bean
of that type and mark it as @Primary
or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder
@Bean
.
Note that, in either case, doing so disables all auto-configuration of the ObjectMapper
.
如果您提供任何`@Beans`,类型为`MappingJackson2HttpMessageConverter`,它们将替换MVC配置中的默认值。同样地,还提供了一个方便的`HttpMessageConverters`类型Bean(如果您使用默认MVC配置,该类型始终可用)。它有一些有用的方法来访问默认和用户增强消息转换器。
If you provide any @Beans
of type MappingJackson2HttpMessageConverter
, they replace the default value in the MVC configuration.
Also, a convenience bean of type HttpMessageConverters
is provided (and is always available if you use the default MVC configuration).
It has some useful methods to access the default and user-enhanced message converters.
有关更多详情,请参阅"`Customize the @ResponseBody Rendering"部分和{code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[`WebMvcAutoConfiguration
]源代码。
See the “Customize the @ResponseBody Rendering” section and the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[WebMvcAutoConfiguration
] source code for more details.
Customize the @ResponseBody Rendering
Spring使用`HttpMessageConverters`来呈现`@ResponseBody`(或`@RestController`的响应)。您可在Spring Boot上下文中添加适当类型的Bean,以贡献其他转换器。如果您添加的Bean属于在任何情况下都将包含的类型(例如,`MappingJackson2HttpMessageConverter`用于JSON转换),它将替换默认值。还提供了一个方便的`HttpMessageConverters`类型Bean,如果您使用默认MVC配置,则它始终可用。它有一些有用的方法来访问默认和用户增强消息转换器(例如,如果您想将它们手动注入定制的`RestTemplate`时,它会很有用)。
Spring uses HttpMessageConverters
to render @ResponseBody
(or responses from @RestController
).
You can contribute additional converters by adding beans of the appropriate type in a Spring Boot context.
If a bean you add is of a type that would have been included by default anyway (such as MappingJackson2HttpMessageConverter
for JSON conversions), it replaces the default value.
A convenience bean of type HttpMessageConverters
is provided and is always available if you use the default MVC configuration.
It has some useful methods to access the default and user-enhanced message converters (For example, it can be useful if you want to manually inject them into a custom RestTemplate
).
与在正常MVC使用中一样,您提供的任何`WebMvcConfigurer`Bean也可以通过覆盖`configureMessageConverters`方法来贡献转换器。但是,与正常MVC不同,您只能提供您需要的额外转换器(因为Spring Boot使用相同的机制来贡献其默认值)。最后,如果您通过提供自己的`@EnableWebMvc`配置退出Spring Boot默认MVC配置,那么您可以通过使用`WebMvcConfigurationSupport`中的`getMessageConverters`完全控制并手动执行所有操作。
As in normal MVC usage, any WebMvcConfigurer
beans that you provide can also contribute converters by overriding the configureMessageConverters
method.
However, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults).
Finally, if you opt out of the Spring Boot default MVC configuration by providing your own @EnableWebMvc
configuration, you can take control completely and do everything manually by using getMessageConverters
from WebMvcConfigurationSupport
.
有关更多详情,请参阅{code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[WebMvcAutoConfiguration
]源代码。
See the {code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[WebMvcAutoConfiguration
] source code for more details.
Handling Multipart File Uploads
Spring Boot包含servlet 5 jakarta.servlet.http.Part`API,以支持文件上传。默认情况下,Spring Boot配置Spring MVC,为每个文件配置最大1MB的大小,在一个请求中的文件数据最大为10MB。您可以覆盖这些值、存储中间数据的位置(例如,到
/tmp`目录)以及使用`MultipartProperties`类中公开的属性将数据刷新到磁盘的阈值。例如,如果您想指定文件不受限制,请将configprop:spring.servlet.multipart.max-file-size[]属性设置为`-1`。
Spring Boot embraces the servlet 5 jakarta.servlet.http.Part
API to support uploading files.
By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request.
You may override these values, the location to which intermediate data is stored (for example, to the /tmp
directory), and the threshold past which data is flushed to disk by using the properties exposed in the MultipartProperties
class.
For example, if you want to specify that files be unlimited, set the configprop:spring.servlet.multipart.max-file-size[] property to -1
.
当您想要接收多部分编码文件数据作为Spring MVC控制器处理程序方法中类型为`MultipartFile`的`@RequestParam`-注释的参数时,多部分支持非常有用。
The multipart support is helpful when you want to receive multipart encoded file data as a @RequestParam
-annotated parameter of type MultipartFile
in a Spring MVC controller handler method.
有关更多详情,请参阅{code-spring-boot-autoconfigure-src}/web/servlet/MultipartAutoConfiguration.java[MultipartAutoConfiguration
]源代码。
See the {code-spring-boot-autoconfigure-src}/web/servlet/MultipartAutoConfiguration.java[MultipartAutoConfiguration
] source for more details.
建议使用容器内置的多部分上传支持,而不是引入一个附加依赖项,如Apache Commons File Upload。 |
It is recommended to use the container’s built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload. |
Switch Off the Spring MVC DispatcherServlet
默认情况下,所有内容都从您的应用程序根目录提供(/
)。如果您希望映射到不同的路径,则可以按如下方式配置一个:
By default, all content is served from the root of your application (/
).
If you would rather map to a different path, you can configure one as follows:
spring: mvc: servlet: path: "/mypath"
如果您有其他servlet,您可以为每个servlet声明类型为`Servlet`或`ServletRegistrationBean`的`@Bean`,Spring Boot将会将它们透明地注册到容器中。因为servlet就是以这种方式注册的,所以它们可以映射到`DispatcherServlet`的子上下文,而不调用它。
If you have additional servlets you can declare a @Bean
of type Servlet
or ServletRegistrationBean
for each and Spring Boot will register them transparently to the container.
Because servlets are registered that way, they can be mapped to a sub-context of the DispatcherServlet
without invoking it.
自己配置`DispatcherServlet`是不太常见的,但如果您确实需要这样做,则还必须提供类型为`DispatcherServletPath`的`@Bean`,以提供您的自定义`DispatcherServlet`的路径。
Configuring the DispatcherServlet
yourself is unusual but if you really need to do it, a @Bean
of type DispatcherServletPath
must be provided as well to provide the path of your custom DispatcherServlet
.
Switch off the Default MVC Configuration
完全控制MVC配置的最简单方法是提供您自己的`@EnableWebMvc`注释的`@Configuration`。这样做会将所有MVC配置都留给您处理。
The easiest way to take complete control over MVC configuration is to provide your own @Configuration
with the @EnableWebMvc
annotation.
Doing so leaves all MVC configuration in your hands.
Customize ViewResolvers
ViewResolver`是Spring MVC的核心组件,它将
@Controller`中的视图名称转换为实际的`View`实现。请注意,ViewResolvers`主要用于UI应用程序,而不是REST风格的服务(`View`不用于呈现
@ResponseBody`)。有多种`ViewResolver`实现可供选择,而且Spring自己不会明确提出意见,建议您使用哪一种。而Spring Boot会根据它在类路径和应用程序上下文中找到的内容,为您安装一个或两个`ViewResolver`。`DispatcherServlet`使用它在应用程序上下文中找到的所有解析器,依次尝试每个解析器,直到获得结果。如果您添加您自己的解析器,您必须注意解析器的顺序和添加的位置。
A ViewResolver
is a core component of Spring MVC, translating view names in @Controller
to actual View
implementations.
Note that ViewResolvers
are mainly used in UI applications, rather than REST-style services (a View
is not used to render a @ResponseBody
).
There are many implementations of ViewResolver
to choose from, and Spring on its own is not opinionated about which ones you should use.
Spring Boot, on the other hand, installs one or two for you, depending on what it finds on the classpath and in the application context.
The DispatcherServlet
uses all the resolvers it finds in the application context, trying each one in turn until it gets a result.
If you add your own, you have to be aware of the order and in which position your resolver is added.
WebMvcAutoConfiguration
将以下 ViewResolvers
添加到您的上下文中:
WebMvcAutoConfiguration
adds the following ViewResolvers
to your context:
-
An
InternalResourceViewResolver
named '`defaultViewResolver’. This one locates physical resources that can be rendered by using theDefaultServlet
(including static resources and JSP pages, if you use those). It applies a prefix and a suffix to the view name and then looks for a physical resource with that path in the servlet context (the defaults are both empty but are accessible for external configuration throughspring.mvc.view.prefix
andspring.mvc.view.suffix
). You can override it by providing a bean of the same type. -
A
BeanNameViewResolver
named '`beanNameViewResolver’. This is a useful member of the view resolver chain and picks up any beans with the same name as theView
being resolved. It should not be necessary to override or replace it. -
A
ContentNegotiatingViewResolver
named '`viewResolver’ is added only if there are actually beans of typeView
present. This is a composite resolver, delegating to all the others and attempting to find a match to the '`Accept’ HTTP header sent by the client. There is a useful blog aboutContentNegotiatingViewResolver
that you might like to study to learn more, and you might also look at the source code for detail. You can switch off the auto-configuredContentNegotiatingViewResolver
by defining a bean named '`viewResolver’. -
If you use Thymeleaf, you also have a
ThymeleafViewResolver
named '`thymeleafViewResolver’. It looks for resources by surrounding the view name with a prefix and suffix. The prefix isspring.thymeleaf.prefix
, and the suffix isspring.thymeleaf.suffix
. The values of the prefix and suffix default to '`classpath:/templates/’ and '`.html’, respectively. You can overrideThymeleafViewResolver
by providing a bean of the same name. -
If you use FreeMarker, you also have a
FreeMarkerViewResolver
named '`freeMarkerViewResolver’. It looks for resources in a loader path (which is externalized tospring.freemarker.templateLoaderPath
and has a default value of '`classpath:/templates/’) by surrounding the view name with a prefix and a suffix. The prefix is externalized tospring.freemarker.prefix
, and the suffix is externalized tospring.freemarker.suffix
. The default values of the prefix and suffix are empty and '`.ftlh’, respectively. You can overrideFreeMarkerViewResolver
by providing a bean of the same name. -
If you use Groovy templates (actually, if
groovy-templates
is on your classpath), you also have aGroovyMarkupViewResolver
named '`groovyMarkupViewResolver’. It looks for resources in a loader path by surrounding the view name with a prefix and suffix (externalized tospring.groovy.template.prefix
andspring.groovy.template.suffix
). The prefix and suffix have default values of '`classpath:/templates/’ and '`.tpl’, respectively. You can overrideGroovyMarkupViewResolver
by providing a bean of the same name. -
If you use Mustache, you also have a
MustacheViewResolver
named '`mustacheViewResolver’. It looks for resources by surrounding the view name with a prefix and suffix. The prefix isspring.mustache.prefix
, and the suffix isspring.mustache.suffix
. The values of the prefix and suffix default to '`classpath:/templates/’ and '`.mustache’, respectively. You can overrideMustacheViewResolver
by providing a bean of the same name.
有关更多详细信息,请参阅以下部分:
For more detail, see the following sections:
-
{code-spring-boot-autoconfigure-src}/web/servlet/WebMvcAutoConfiguration.java[
WebMvcAutoConfiguration
] -
{code-spring-boot-autoconfigure-src}/thymeleaf/ThymeleafAutoConfiguration.java[
ThymeleafAutoConfiguration
] -
{code-spring-boot-autoconfigure-src}/freemarker/FreeMarkerAutoConfiguration.java[
FreeMarkerAutoConfiguration
] -
{code-spring-boot-autoconfigure-src}/groovy/template/GroovyTemplateAutoConfiguration.java[
GroovyTemplateAutoConfiguration
]