Content Types

您可以配置 Spring MVC 从请求(例如,“Accept”标头、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).

默认情况下,仅检查“Accept”标头。

By default, only the Accept header is checked.

如果您必须使用基于 URL 的内容类型解析,请考虑使用查询参数策略而不是路径扩展名。有关详情,请参阅 Suffix MatchSuffix Match and RFD

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.

您可以自定义请求的内容类型解析,如下例所示:

You can customize requested content type resolution, as the following example shows:

  • Java

  • Kotlin

  • Xml

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.mediaType("json", MediaType.APPLICATION_JSON);
		configurer.mediaType("xml", MediaType.APPLICATION_XML);
	}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
		configurer.mediaType("json", MediaType.APPLICATION_JSON)
		configurer.mediaType("xml", MediaType.APPLICATION_XML)
	}
}
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
	<value>
		json=application/json
		xml=application/xml
	</value>
</property>
</bean>