不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2021-05-31 10:37:19  修改时间:2024-04-22 23:44:27  分类:Java框架/系统  编辑

目前流行的接口形式,数据类型基本都是json格式,很少使用xml格式进行数据传输。

在网站seo时,常常会用到sitemap,常用的形式就是xml格式。

如下简单说明:

1. 在xml返回的实体类前加@XmlRootElement注解。

@XmlRootElement
public class Urlset {

    private List<Url> url = new ArrayList<>();
    
    @XmlRootElement
    public static class Url {
        private String loc;
        private String lastmod;
        private String changefreq;
        private String priority;
        ...
    }
}

如果实体类中包含其他实体类,则需要在子类的前面也添加@XmlRootElement注解。

2. 在请求的注释中添加 produces = {"application/xml;charset=UTF-8"}

@RequestMapping(value = "/sitemap.xml", produces = {"application/xml;charset=UTF-8"}, method = RequestMethod.GET)
private Urlset getSitemapXml() {
    Urlset urlset = new Urlset();
    Url url = new Url();
    url.setLoc("");
    url.setLastmod("");
    url.setChangefreq("");
    url.setPriority("");
    urlset.getUrl().add(url);
    ...
}

请求返回结果如:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset>
    <url>
        <changefreq>daily</changefreq>
        <lastmod>2018-07-16</lastmod>
        <loc>/590.html</loc>
        <priority>0.8</priority>
    </url>
    <url>
        <changefreq>daily</changefreq>
        <lastmod>2018-07-16</lastmod>
        <loc>/1972.html</loc>
        <priority>0.8</priority>
    </url>
</urlset>

 

 

参考:

Spring Boot rest api 返回 XML 格式的数据

Spring Boot返回xml格式

Spring Boot通过过滤器实现对请求头的修改