自学内容网 自学内容网

springboot 接口接收及响应xml数据

1.实体类

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.接口

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
在这里插入图片描述


原文地址:https://blog.csdn.net/qq_35359474/article/details/142495404

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!