springboot 如何为网站添加网站地图(sitemap)功能?

sitemap 能够更方便的使搜索引擎抓取,springboot 要如何为网站添加网站地图(sitemap)功能呢?

1 个解决方案

AllenJiang
中间件研发,关注微信公众号 : 小哈学Java, 回复"666", 即可免费领取10G学习&面试资料

第一步:添加 maven 依赖

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

sitemapgen4j 的 GitHub 地址:https://github.com/dfabulich/sitemapgen4j

第二步:添加接口 /sitemap.xml

	@Autowired
	private SEOService seoService;
	
	/**
     * site map
     *
     * @return
     */
    @GetMapping("/sitemap.xml")
    public void createSiteMapXml(HttpServletResponse response) throws IOException {
	  response.setContentType(MediaType.APPLICATION_XML_VALUE);
        Writer writer = response.getWriter();
        writer.append(seoService.createSiteMapXmlContent());
    }

service 实现类代码如下:

@Value("${domain}")
private String domain;
@Autowired
private QuestionMapper questionMapper;

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

        WebSitemapGenerator wsg = null;
        try {wsg = new WebSitemapGenerator(baseUrl);
            // 首页 url
            WebSitemapUrl url = new WebSitemapUrl.Options(baseUrl + "/home")
                    .lastMod(dateTimeFormatter.format(LocalDateTime.now())).priority(1.0).changeFreq(ChangeFreq.DAILY).build();
            wsg.addUrl(url);

            // 查询所有的问题方案数据
            List<Question> questions = questionMapper.queryAllQuestions();

			// 动态添加 url
            for (Question question : questions) {
		WebSitemapUrl tmpUrl = new WebSitemapUrl.Options(baseUrl + "/question/" + question.getId()) 
.lastMod(dateTimeFormatter.format(question.getUpdateTime())).priority(0.9).changeFreq(ChangeFreq.DAILY).build();
                wsg.addUrl(tmpUrl);
            }
        } catch (Exception e) {log.error("create sitemap xml error:", e);
        }
        return String.join("", wsg.writeAsStrings());
    }

代码写好后,重启项目,请求 /sitemap.xml 接口,可以放回 xml 数据如下:

这里需要对 sitemap.xml 的子节点的参数做下说明:

  • loc 表示完整网址,必填项,长度不得超过 256 字节
  • lastmod 表示本网页最后修改时间,
  • changefreq 表示更新频率,可选值:always、hourly、daily、weekly、monthly、yearly、never
  • priority 用来指定此链接相对于其他链接的优先权比值,可选值 0.0-1.0,一般来说网站首页 1.0,然后二级三级页面依次降低,具体这个属性有多重要不太清楚。

以上 4 项中,除了 loc 是必填项之外,其它 3 个都不是必须的,但最好都写上。

一个 sitemap 文件包含的网址不得超过 5 万个,且文件大小不得超过 10 MB。如果您的 sitemap 超过了这些限值,请将其拆分为几个小的 sitemap。