內容型別

你可以配置 Spring MVC 如何從請求中確定請求的媒體型別(例如,Accept 頭、URL 路徑副檔名、查詢引數等)。

預設情況下,只檢查 Accept 頭。

如果必須使用基於 URL 的內容型別解析,考慮使用查詢引數策略而非路徑副檔名。更多詳情請參閱字尾匹配字尾匹配和 RFD

你可以自定義請求的內容型別解析,示例如下:

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