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

Spring3+JDK6 REST服务JSON正常XML请求报400,如何适配XML输入?

解决Spring 3 REST服务无法接收XML请求的400错误问题

看起来你的服务已经配置了支持JSON和XML的consumes和produces,但XML请求返回400,主要是两个核心问题:XML请求根元素与DTO的JAXB注解不匹配,以及Spring MVC可能未正确配置XML消息转换器,下面是具体的解决步骤:

1. 修正DTO的XML根元素注解

你的EstDto使用了@XmlRootElement但未指定name属性,JAXB默认会将根元素命名为类名的首字母小写(也就是estDto),但你的XML请求里用的是<root>节点,这直接导致JAXB无法解析请求体,返回400错误。

修改EstDto的注解,指定根元素名称为root,匹配你的请求结构:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "root") // 关键:指定根元素名称为root
@XmlAccessorType(XmlAccessType.FIELD)
public class EstDto implements Serializable {
    private long regionCode;
    private String medicalReportYN;
}

2. 配置Spring MVC的XML消息转换器

Spring 3.2默认不会自动注册JAXB的消息转换器,需要显式配置Jaxb2RootElementHttpMessageConverter来处理XML请求和响应:

如果你用XML配置Spring MVC:

在spring-servlet.xml中添加消息转换器配置:

<mvc:annotation-driven>
    <mvc:message-converters>
        <!-- 保留JSON转换器,使用Jackson 2 -->
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        <!-- 添加XML转换器,支持JAXB解析 -->
        <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

如果你用Java配置Spring MVC:

继承WebMvcConfigurerAdapter并重写消息转换器配置方法:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 添加JSON转换器
        converters.add(new MappingJackson2HttpMessageConverter());
        // 添加XML转换器
        converters.add(new Jaxb2RootElementHttpMessageConverter());
    }
}

3. 清理依赖冲突

你的pom.xml中同时引入了Jackson 1(jackson-mapper-asl)和Jackson 2(jackson-databind),这可能导致版本冲突,建议移除Jackson 1的依赖,只保留Jackson 2:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>
<!-- 仅保留Jackson 2依赖 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.0</version>
</dependency>

注:JDK 6自带JAXB的API和实现,不需要额外添加JAXB相关依赖。

4. 验证请求头

发送XML请求时,务必确保Content-Type请求头设置为application/xml,否则Spring会无法识别请求格式,依然返回400。

完成以上步骤后,你的XML请求应该就能被正常解析,返回正确结果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:53:02