Java生成sitemap网站地图

2023-04-25后端1 分钟134 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

前言

sitemap站点地图是让搜索引擎能够收录你网站的内容,提高你的网站访问量。

代码实现

引入sitemapgen4j依赖

xml 复制代码
<dependency>
    <groupId>com.github.dfabulich</groupId>
    <artifactId>sitemapgen4j</artifactId>
    <version>1.1.1</version>
</dependency>

编写生成 sitemap 代码

java 复制代码
public void generateSitemap() {
    String tempPath = "/mydata/nginx/html/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();
    }
}

服务器配置

nginx 复制代码
server {
    listen          端口;
    server_name     域名;
    charset utf8;

    access_log logs/access.log  main;

    location / {
        alias /mydata/nginx/html/seo/;
        sendfile on;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句