springboot入参为xml返回xml

原创
2020/04/16 21:29
阅读数 933

一.引入springboot的(响应xml)的依赖

<!--引入响应xml的依赖-->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

二.在controller层入参与出参处理

TeacherController

package com.huawei.controller;

import com.huawei.pojo.Teacher;
import com.huawei.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author jose
 * date 2020
 */
@RestController
public class TeaacherController {
    @Autowired
    private TeacherService teacherService;
    @RequestMapping(value="/getTeacher",consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    //注意;consumes注解用于标识,该方法接受xml参数,并反序列化为对应的对象;
    //  produces注解用于标识,该方法的返回值为xml参数,将返回的对象序列化为xml,
    public Teacher getTeacher(@RequestBody Teacher teacher){
        Teacher result =teacherService.getTeacher(teacher);
        return result;
    }
}

三.在实体类设置属性与类为xml

package com.huawei.pojo;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * @Author jose
 * date 2020
 */
@JacksonXmlRootElement(localName = "Teacher") //映射xml的根标签名称为Teacher;
public class Teacher  {

    @JacksonXmlProperty(localName = "tid")
    //映射每一个属性为一个标签,可指定生成的标签名
    private int tid;

    @JacksonXmlProperty(localName = "tname")
    private String tname;

    @JacksonXmlProperty(localName = "tcid")
    private int tcid;

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    public int getTcid() {
        return tcid;
    }

    public void setTcid(int tcid) {
        this.tcid = tcid;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "tid=" + tid +
                ", tname='" + tname + '\'' +
                ", tcid=" + tcid +
                '}';
    }
}

参考文档:https://www.pianshen.com/article/5375123901/

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部