內容類型

您可以組態 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>