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 小时前
真的,你可以不用TypeScript
前端·后端·程序员
郑州光合科技余经理3 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
李慕婉学姐4 小时前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
掘金酱4 小时前
「寻找年味」 沸点活动|获奖名单公示🎊
前端·人工智能·后端
颜酱4 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
QQ5110082855 小时前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe5 小时前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
玹外之音5 小时前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
what丶k5 小时前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
ATCB5 小时前
零门槛!PythonAnywhere 免费部署全指南:不止 Django,这些项目都能搭(附主流平台对比)
后端·python·django