需要给开始计划去做的bbs来点seo,因此计划添加一个sitemap.xml,网上就找到这样一个简单的示例。
首先需要这样一个控制器,用来指向sitemap.xml
@Controller
public class SitemapController {
@RequestMapping(value = "/sitemap.xml", method = RequestMethod.GET)
@ResponseBody
public XmlUrlSet main() {
XmlUrlSet xmlUrlSet = new XmlUrlSet();
create(xmlUrlSet, "", XmlUrl.Priority.HIGH);
create(xmlUrlSet, "/posts",XmlUrl.Priority.MEDIUM);
return xmlUrlSet;
}
private void create(XmlUrlSet xmlUrlSet, String link, XmlUrl.Priority priority) {
xmlUrlSet.addUrl(new XmlUrl("http://thoughtworksbbs.phodal.com" + link, priority));
}
}
这样我们就可以控制对sitemap.xml的HTTP请求。
@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;
{
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
lastmod = formatter.format(new Date(System.currentTimeMillis()));
}
@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;
}
}
@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 xmlUrls = new ArrayList();
public void addUrl(XmlUrl xmlUrl) {
xmlUrls.add(xmlUrl);
}
public Collection getXmlUrls() {
return xmlUrls;
}
}
这样生成的还有点小问题,Google认为有bug,所以还需要一个package-info.java,在stackoverflow上看到的。
@XmlSchema(namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
elementFormDefault = QUALIFIED, xmlns = {@XmlNs(prefix = "",
namespaceURI = "http://www.sitemaps.org/schemas/sitemap/0.9")})
package com.thoughtworks.bbs.web.sitemap;
import static javax.xml.bind.annotation.XmlNsForm.QUALIFIED;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;
围观我的Github Idea墙, 也许,你会遇到心仪的项目