You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何强制Spring Boot的@RequestBody接收XML,解决类型不支持错误

问题根因

Spring Boot 内置默认仅集成了 Jackson 处理 JSON 格式的序列化/反序列化能力,未自带 XML 格式的消息转换依赖。即使接口指定了consumes = APPLICATION_XML_VALUE,Spring Web 找不到可处理application/xml类型的HttpMessageConverter,就会抛出「Content type not supported」错误,走默认的 JSON 处理逻辑。

解决步骤
  • 第一步:引入 Jackson XML 处理依赖
    如果是 Maven 项目,在pom.xml中添加:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

如果是 Gradle 项目,在build.gradle中添加:

implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
  • 第二步:给 POJO 类添加 XML 绑定注解
    需要通过注解明确 Java 类字段和 XML 节点、属性的映射关系,修改后的类定义如下:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement

@JacksonXmlRootElement(localName = "users")
class Users {
    @JacksonXmlProperty(localName = "user")
    @JacksonXmlElementWrapper(useWrapping = false) // 禁止给List再加一层外层包裹节点
    List<UserDTO> user
}

class UserDTO {
    @JacksonXmlProperty(isAttribute = true) // 标记对应XML节点的属性
    String name
    @JacksonXmlProperty(isAttribute = true)
    String age
}
  • 第三步:确认请求头配置
    请求时需明确携带Content-Type: application/xml;charset=UTF-8头,避免被框架识别为其他格式。

额外提示:你现有控制器代码中的println user.name存在变量未定义的问题,正确写法应该是从绑定的request参数中取user列表遍历取值,比如request.user.each { println "${it.name} : ${it.age}" }

完成以上配置后重启应用,即可正常接收XML格式的请求体并完成参数绑定。

内容的提问来源于stack exchange,提问作者Blazerg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:36:03