spring mvc 返回xml格式数据

1.问题 : 因为业务需要,需要发送xml格式的数据,使用spring mvc 自己解析,就不用费心去自己搞这些东西.

2.解决:

新建一个实体类,直接在实体类中添加注解即可,如下:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class XMlTestBean {
    @XmlElement
    @XmlCDATA
    private String username;
    @XmlElement
    private String password;
    @XmlElement
    private String name;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "XMlTestBean [username=" + username + ", password=" + password + ", name=" + name + "]";
    }
    
    
}

类上方添加:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)

字段名添加:

@XmlElement

在controller类中返回即可:

@Controller
@RequestMapping("test")
public class TestController {
    
    @RequestMapping("xml")
    @ResponseBody
    public XMlTestBean getTestXML(){
        XMlTestBean xml = new XMlTestBean();
        xml.setUsername("aa");
        xml.setPassword("bb");
        xml.setName("cc");
        return xml;
    }
    @RequestMapping("getXml")
    public void getXml(@RequestBody XMlTestBean xml){
        System.out.println(xml);
    }
    

}

结果:

<?xml version="1.0" encoding="UTF-8"?>
<xMlTestBean>
    <username>
        <![CDATA[aa]]>
    </username>
    <password>bb</password>
    <name>cc</name>
</xMlTestBean>

 

补充:@XmlCDATA注解的作用:可以让返回值中添加

<![CDATA[]]>

 CDATA 区段,可以不被XML解析器解析,但是需要在pom.xml添加

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.5.0</version>
</dependency>

和在实体类的包下添加jaxb.properties文件,文件内容如下:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

 

只是解决了问题,但是原理这些还不懂,Σ( ° △ °|||)︴,有机会再搞懂原理吧

posted @ 2018-10-26 11:21  随意的马蒂洛克  阅读(2518)  评论(0编辑  收藏  举报