Skip to content

内容协商

在响应式栈中查看等效项

您可以配置 Spring MVC 如何从请求中确定请求的媒体类型(例如,通过 Accept 标头、URL 路径扩展名、查询参数等)。

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

如果您必须使用基于 URL 的内容类型解析,请考虑使用查询参数策略而非路径扩展。有关更多详细信息,请参阅 后缀匹配后缀匹配与 RFD

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

java
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

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

	override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
		configurer.mediaType("json", MediaType.APPLICATION_JSON)
		configurer.mediaType("xml", MediaType.APPLICATION_XML)
	}
}
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>

补充教学

1. 什么是内容协商?

内容协商(Content Negotiation)是 HTTP 协议的一项特性,允许客户端和服务器之间就响应资源的“表现形式”(如 JSON、XML、HTML)达成一致。

2. 常见的协商策略

  • Accept Header: 客户端通过 Accept: application/json 告诉服务器它想要的数据格式。这是最标准的做法。
  • Query Parameter: 通过 URL 参数显式指定,如 /api/users?format=json。在浏览器调试或无法方便修改 Header 的情况下非常有用。
  • Path Extension: 通过后缀指定,如 /api/users.json(Spring 官方已不再推荐此方式,建议使用参数)。

3. 配置建议

在现代 RESTful API 开发中,通常建议优先使用 Accept Header。如果需要支持浏览器直接预览或简单客户端访问,可以额外开启 Query Parameter 策略。

Based on Spring Framework.