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

相关推荐
左左右右左右摇晃3 分钟前
Java笔记——JMM
java·后端·spring
Java编程爱好者15 分钟前
面试官:“你一天烧几十个token也好意思面AI应用开发?”我镇定自若:“我烧的不是token,是我的热情。”面试官:“明天二面。”
后端
Memory_荒年18 分钟前
Nacos双面超人:注册中心 + 配置中心,一个都不能少!
java·后端·架构
Memory_荒年18 分钟前
Nacos 面试通关宝典:从入门到源码,你值得拥有!
后端
shepherd11122 分钟前
别再无脑 cat 了!后端排查 GB 级生产日志的实战命令
linux·后端
AI茶水间管理员31 分钟前
谁在掌控大模型的创造力开关?Temperature & Top-p
人工智能·后端
打酱油的D1 小时前
01. Node.js 运行时
前端·后端
Moe4881 小时前
Redis 缓存三大经典问题:穿透、击穿与雪崩
java·后端·面试
我爱娃哈哈1 小时前
SpringBoot + JSON 字段 + MySQL 8.0 函数索引:灵活存储半结构化数据,查询不慢
后端
哆啦A梦15882 小时前
统一返回包装类 Result和异常处理
java·前端·后端·springboot