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 分钟前
一次 SaaS ERP 主数据生命周期设计:Policy、PreCheck 与结构化阻断原因
java·后端·架构·saas
苏三说技术18 分钟前
Redis已正式接入AI
后端
思考着亮24 分钟前
11.Redis与Cache-Aside旁路缓存策略
后端
catino24 分钟前
spring-Bean
java·后端·spring
深入云栈36 分钟前
Netty 4.2.x 源码深度解析 (十一):EventExecutor 业务线程池 —— 防止 IO 线程阻塞的并发模型
java·后端
柠檬味拥抱44 分钟前
鸿蒙 AI 对话实战:用蓝耘 MaaS 给礼物 App 装上「多轮对话选礼大脑」
后端
唐青枫1 小时前
别再把 build.zig 当配置文件:Zig 构建系统从零到实战
后端
Naylor1 小时前
只借不占:Rust 的引用与借用
后端·rust
大勇前进1 小时前
Python装饰器、生成器、上下文管理器:3个必会的"魔法"机制
后端
Go_error1 小时前
Fyne:让 Go 开发者也能玩转 GUI
后端·go