springboot 接口接收及响应xml数据

1.实体类

java 复制代码
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) // 指示JAXB直接访问类的字段而不是getter/setter方法
public class User {
    @XmlElement // 表示这个字段应该被映射为XML的一个元素
    private String name;

    @XmlElement // 表示这个字段应该被映射为XML的一个元素
    private int age;

    // 构造方法、getter和setter省略

    public User() {}

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 和 Setter
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.接口

java 复制代码
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	//consumes 将接收到的xml数据自动转为user对象,produces 将返回user对象自动转为xml数据返回
    @PostMapping(value = "/user", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public User createUser(@RequestBody User user) {
        // 在这里可以添加处理逻辑,例如保存到数据库
        // 这里只是简单返回接收到的用户对象
        user.setAge(102);
        return user;
    }
}

3.测试

设置Content-Type

设置raw 为xml

相关推荐
小江的记录本5 分钟前
【JVM虚拟机】垃圾回收GC:四种引用类型:强引用、软引用、弱引用、虚引用(附《思维导图》+《面试高频考点清单》)
java·jvm·spring boot·后端·python·spring·面试
小马爱打代码37 分钟前
Spring源码 第四篇:Spring 5 源码深度拆解:AOP 全流程核心原理
java·后端·spring
ServBay1 小时前
2026 Mac 本地大模型部署深度解析与混合架构指南
后端·macos·aigc
一拳一个娘娘腔2 小时前
【SRC漏洞挖掘系列】第10期:GraphQL & API 安全 —— 现代 API 的“裸奔”时代
后端·安全·graphql
ZhengEnCi2 小时前
01-如何监听接口调用情况?
java·spring boot·后端
苏渡苇3 小时前
Spring Cloud Alibaba:将 Sentinel 熔断限流规则持久化到 Nacos 配置中心
数据库·spring boot·mysql·spring cloud·nacos·sentinel·持久化
小马爱打代码4 小时前
Spring源码 第九篇:Spring 5 源码深度拆解 - Spring 事件驱动模型
java·后端·spring
ForgeAI码匠4 小时前
ForgeAdmin|Spring Boot 3 后台框架的自动配置设计:少写配置,多做组合
java·spring boot·后端
IT_陈寒4 小时前
为什么 Java 的 Optional 让我调试到深夜?
前端·人工智能·后端
用户8356290780515 小时前
用 Python 实现 Excel 散点图绘制与定制
后端·python