建站以来,试过好多方法实现 sitemap.xml ,从最早的手动更新,到后来每次更新自动写入本地io文件。一方面感觉太零零散散,另外实时的程度不高,再加上好多ZZ引擎,sitemap的要求还能和别人不一样。。。总之最终决定写个动态的,通过springboot的GET接口返回字符串实现,xml结构不复杂,就自己拼。

共计3部分:

其中sitemap类是封装sitemap的实体类;提供了一个简单的Utils,超级简单可以忽略。还有一个在Controller中使用Demo.

SiteMap类:注意有参、全参构造方法,已经重写了toString为了符号xml要求。

import com.ruoyi.common.utils.DateUtils;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @date 2020/7/8 9:45
 */
public class SiteMap {
    
    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd");
    /**
     * url https://www.xxx.com
     */
    private String loc;
    /**
     * 最后更新时间 yyyy-MM-dd
     */
    private Date lastmod;
    /**
     * 更新速度 always hourly daily weekly monthly yearly never
     */
    private String changefreq;
    /**
     * 权重 1.0 0.9 0.8
     */
    private String priority;


    @Override
    /** 重写 toString 适应xml格式 */
    public String toString() {
        StringBuffer sb= new StringBuffer();
        sb.append("<url>");
        sb.append("<loc>" +loc+ "</loc>");
        sb.append("<lastmod>" + sdf.format(lastmod) + "</lastmod>");
        sb.append("<changefreq>" +changefreq+ "</changefreq>");
        sb.append("<priority>" +priority+ "</priority>");
        sb.append("</url>");
        return sb.toString();
    }

    public SiteMap() {
    }

   public SiteMap(String loc) {
     this.loc=loc;
    this.lastmod= new Date();
    this.changefreq= SiteMapUtils.CHANGEFREQ_ALWAYS;
    this.priority= "1.0";
}
  
    public SiteMap(String loc, Date lastmod, String changefreq, String priority) {
        this.loc=loc;
        this.lastmod=lastmod;
        this.changefreq=changefreq;
        this.priority=priority;
    }

}

 

最后在Controller中这样用:

@Controller
public class SiteMapController {

    @Autowired
    private IArticleService articleService;
    public static String BEGIN_DOC = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";

    static String END_DOC = "</urlset>";
    static String CHANGEFREQ_DAILY = "daily";
    public static String CHANGEFREQ_ALWAYS = "always";


    @GetMapping(value = "/sitemap.xml", produces = {"application/xml"})
    @ResponseBody
    public String getSiteMap() {
        StringBuffer sb = new StringBuffer();
        sb.append(BEGIN_DOC);//拼接开始部分
        sb.append(new SiteMap("http://wwww.xxxx.com"));//拼接网站首页地址
        //下面是根据实际情况写,目的是生成整站的Url
        List<Article> articles = articleService.selectArticleListRandom10();
        for (Article a : articles) {
            sb.append(new SiteMap("http://wwww.xxxx.xxx/article/" + a.getId() + ".html", a.getUpdateTime(), CHANGEFREQ_DAILY, "0.9"));
        }
        sb.append(END_DOC);//拼接结尾
        return sb.toString();
    }
}