此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

内容类型

您可以配置 Spring MVC 如何从请求中确定请求的媒体类型 (例如,Acceptheader、URL 路径扩展名、查询参数等)。spring-doc.cadn.net.cn

默认情况下,只有Accept标头。spring-doc.cadn.net.cn

如果必须使用基于 URL 的内容类型解析,请考虑使用 query 参数 策略 over 路径扩展。请参阅后缀匹配和后缀匹配和 RFD 更多细节。spring-doc.cadn.net.cn

可以自定义请求的内容类型分辨率,如以下示例所示:spring-doc.cadn.net.cn

@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>