Springboot生成sitemapXML文件

首先需要编写对应的依赖项,如下代码所示。

        <!--sitemap-->
        <dependency>
            <groupId>com.github.dfabulich</groupId>
            <artifactId>sitemapgen4j</artifactId>
            <version>1.1.1</version>
        </dependency>

接下来编写一个SEO服务,如下代码所示。

import com.redfin.sitemapgenerator.ChangeFreq;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class SEOServiceImpl implements ISEOService {

    @Autowired
    private INewsReportService newsReportService;

    @Override
    public String createSiteMapXmlContent() {
        String domain = "根目录";
        String baseUrl = String.format("https://%s", domain);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        WebSitemapGenerator wsg = null;
        try {
            wsg = new WebSitemapGenerator(baseUrl);
            for (String itemUrl : getFixedUrl()) {
                WebSitemapUrl url = new WebSitemapUrl.Options(baseUrl + itemUrl)
                        .lastMod(dateTimeFormatter.format(LocalDateTime.now())).priority(1.0).changeFreq(ChangeFreq.DAILY).build();
                wsg.addUrl(url);
            }

            // 查询所有的新闻
            List<NewsReport> newsReportList = newsReportService.list();
            for (NewsReport newsItem : newsReportList) {
                WebSitemapUrl tmpUrl = new WebSitemapUrl.Options(baseUrl + "/news/news-detail?id=" + newsItem.getId())
                        .lastMod(dateTimeFormatter.format(newsItem.getCreatedAt())).priority(0.9).changeFreq(ChangeFreq.DAILY).build();
                wsg.addUrl(tmpUrl);
            }
        } catch (Exception e) {

        }
        return String.join("", wsg.writeAsStrings());
    }
    // 固定地址
    private List<String> getFixedUrl() {
        List<String> urlList = new ArrayList<String>();
        urlList.add("/");
        urlList.add("/cities");
        urlList.add("/news");
        urlList.add("/aboutUs");
        return urlList;
    }
}

接下来编写路由,如下代码所示。

    /**
     * sitemap
     * @param response
     * @throws IOException
     */
    @RequestMapping("/sitemap.xml")
    public void createSiteMapXml(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_XML_VALUE);
        Writer writer = response.getWriter();
        writer.append(seoService.createSiteMapXmlContent());
    }

链接