我有一些Java代码来生成我的站点地图。突然停止工作。
当我输入https://example.com/sitemap.xml时,它会返回未格式化的站点地图,我想是因为它已在Google Search Console中被拒绝。
这是一个Spring Boot 2.0.5 RELEASE项目。
SitemapController.java ==>
@Controller
public class SitemapController {
@RequestMapping("/sitemap.xml")
@ResponseBody
public XmlUrlSet main() {
XmlUrlSet xmlUrlSet = new XmlUrlSet();
create(xmlUrlSet, "/", XmlUrl.Priority.HIGH);
return xmlUrlSet;
}
private void create(XmlUrlSet xmlUrlSet, String link, XmlUrl.Priority priority) {
xmlUrlSet.addUrl(new XmlUrl("https://example.com" + link, priority));
}
}
XmlUrl.java ==>
@XmlAccessorType(value = XmlAccessType.NONE)
@XmlRootElement(name = "url")
public class XmlUrl {
public enum Priority {
HIGH("1.0"), MEDIUM("0.5");
private String value;
Priority(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@XmlElement
private String loc;
@XmlElement
private String lastmod = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
@XmlElement
private String changefreq = "daily";
@XmlElement
private String priority;
public XmlUrl() {
}
public XmlUrl(String loc, Priority priority) {
this.loc = loc;
this.priority = priority.getValue();
}
public String getLoc() {
return loc;
}
public String getPriority() {
return priority;
}
public String getChangefreq() {
return changefreq;
}
public String getLastmod() {
return lastmod;
}
}
XmlUrlSet.java ==>
@XmlAccessorType(value = XmlAccessType.NONE)
@XmlRootElement(name = "urlset", namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")
public class XmlUrlSet {
@XmlElements({@XmlElement(name = "url", type = XmlUrl.class)})
private Collection<XmlUrl> xmlUrls = new ArrayList<XmlUrl>();
public void addUrl(XmlUrl xmlUrl) {
xmlUrls.add(xmlUrl);
}
public Collection<XmlUrl> getXmlUrls() {
return xmlUrls;
}
}
package-info.java ==>
@XmlSchema(
namespace="http://www.sitemaps.org/schemas/sitemap/0.9",
elementFormDefault=XmlNsForm.QUALIFIED)
package com.example.utility;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;
我期待这样的输出:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://example.com/</loc>
<lastmod>2017-09-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
</urlset>
但是我得到了一些这样的未格式化XML:
https://example.com/2019-07-09daily1.0
请帮助!
答案 0 :(得分:0)
找到了解决方案!它需要更改控制器以放置“生产”参数,如下所示:
@RequestMapping(value="/sitemap.xml", produces = MediaType.TEXT_XML_VALUE)