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

相关推荐
米羊1212 小时前
Struts 2 漏洞(上)
java·后端·struts
梵得儿SHI2 小时前
Spring Cloud 实战攻坚:企业级用户服务开发(注册登录 + JWT 认证 + 权限控制)
后端·spring·spring cloud·用户注册与登录·jwt无状态认证体系·rbac权限控制·微服务用户中心
callJJ6 小时前
Spring Bean 生命周期详解——从出生到销毁,结合源码全程追踪
java·后端·spring·bean·八股文
怒放吧德德6 小时前
AsyncTool + SpringBoot:轻量级异步编排最佳实践
java·后端
毅炼6 小时前
Java 集合常见问题总结(1)
java·后端
utmhikari7 小时前
【架构艺术】治理后端稳定性的一些实战经验
java·开发语言·后端·架构·系统架构·稳定性·后端开发
undefinedType7 小时前
Rails ActiveSupport::Cache 缓存存储详解
后端
茶杯梦轩7 小时前
从零起步学习并发编程 || 第二章:多线程与死锁在项目中的应用示例
java·服务器·后端
大尚来也7 小时前
深入理解 Android 消息机制:Handler、Looper 与 MessageQueue 的协同工作原理
后端
sp427 小时前
Spring Task 任务调度可视化管理
后端·spring