引言
在实际开发中,我们经常需要让接口同时支持多种数据格式(如 JSON、XML),以满足不同客户端的请求需求。例如:
-
前端页面默认使用 JSON 格式;
-
第三方系统要求返回 XML 格式。
一、Spring MVC 内容协商原理
Spring MVC 的 ContentNegotiation 机制可以根据请求参数或 Accept 头自动选择响应格式。其核心逻辑如下:
-
客户端发起请求时,通过 URL 参数 或 Accept 头 声明期望的数据格式。
-
服务端根据配置的
MediaType匹配对应的消息转换器(如Jackson2HttpMessageConverter)。 -
最终返回对应格式的数据。
二、配置内容协商策略
以下是关键配置代码:
package com.kjwl.framework.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorParameter(true)
// 客户端请求url需要携带一个query参数 默认名称是 format
.parameterName("format")
.ignoreAcceptHeader(true) // 忽略Accept头,强制使用默认类型
// 如果不声明 该query参数 返回的是json 如果你想指定默认返回类型就需要声明
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML);
}
}
三、配置解析
-
favorParameter(true)允许通过 URL 参数(如
?format=xml)指定返回格式。默认参数名为format,可通过parameterName()自定义。 -
ignoreAcceptHeader(true)是否忽略客户端的
Accept头。若设置为true,则强制使用 URL 参数或默认格式;若为false,则优先使用Accept头。 -
defaultContentType()未指定格式时,默认返回 JSON。
-
mediaType()注册支持的格式映射。例如,
format=xml对应APPLICATION_XML。
四、实现 XML 支持
仅仅配置内容协商还不够! 需添加 XML 消息转换器依赖:
<!-- Maven 依赖:Jackson XML 处理 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Spring Boot 会自动检测该依赖,并注册 MappingJackson2XmlHttpMessageConverter。
五、接口使用示例
@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
return new User("tom", "tom@example.com");
}
}
测试请求:
-
默认返回 JSON
GET /user
响应:{"name": "tom", "email": "tom@example.com"}
-
通过参数返回 XML
GET /user?format=xml
响应:
<User>
<name>tom</name>
<email>tom@example.com</email>
</User>