导入sitemapgen4j:
<dependency>
<groupId>com.github.dfabulich</groupId>
<artifactId>sitemapgen4j</artifactId>
<version>1.1.1</version>
</dependency>
使用示例:
public void generateSitemap() {
String tempPath = "/home/seo";
//String tempPath = System.getProperty("java.io.tmpdir") + File.separator + "/seo/";
File file = new File(tempPath);
if (!file.exists()) {
file.mkdirs();
}
String domain = "https://www.domain.com";
try {
WebSitemapGenerator g1 = WebSitemapGenerator.builder(domain, file)
.fileNamePrefix("article").build();
Date date = new Date();
for (int i = 1; i < 21; i++) {
WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/article/" + i ).lastMod(date).build();
g1.addUrl(url);
}
WebSitemapGenerator g2 = WebSitemapGenerator.builder(domain, file)
.fileNamePrefix("issue").build();
Date date2 = new Date();
for (int i = 1; i < 21; i++) {
WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/issue/" + i ).lastMod(date2).build();
g2.addUrl(url);
}
List<String> fileNames = new ArrayList<>();
// 生成 sitemap 文件
List<File> articleFiles = g1.write();
articleFiles.forEach(e -> fileNames.add(e.getName()));
List<File> issueFiles = g2.write();
issueFiles.forEach(e -> fileNames.add(e.getName()));
// 构造 sitemap_index 生成器
W3CDateFormat dateFormat = new W3CDateFormat(W3CDateFormat.Pattern.DAY);
SitemapIndexGenerator sitemapIndexGenerator = new SitemapIndexGenerator
.Options(domain, new File(tempPath + "sitemap_index.xml"))
.dateFormat(dateFormat)
.autoValidate(true)
.build();
fileNames.forEach(e -> {
try {
// 组装 sitemap 文件 URL 地址
sitemapIndexGenerator.addUrl(tempPath + e);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
});
// 生成 sitemap_index 文件
sitemapIndexGenerator.write();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}