15
服务器sitemap.xml
和robots.txt
与Spring MVC
的最佳方式是什么?我希望以最简洁的方式通过Controller
来处理这些文件。使用Spring MVC服务sitemap.xml和robots.txt
服务器sitemap.xml
和robots.txt
与Spring MVC
的最佳方式是什么?我希望以最简洁的方式通过Controller
来处理这些文件。使用Spring MVC服务sitemap.xml和robots.txt
我依靠JAXB为我生成sitemap.xml。
我的控制器看起来像下面,和我有一些数据库表来跟踪我希望出现在网站地图的链接: -
SitemapController.java
@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, "/link-1", XmlUrl.Priority.HIGH);
create(xmlUrlSet, "/link-2", XmlUrl.Priority.MEDIUM);
// for loop to generate all the links by querying against database
...
return xmlUrlSet;
}
private void create(XmlUrlSet xmlUrlSet, String link, XmlUrl.Priority priority) {
xmlUrlSet.addUrl(new XmlUrl("http://www.mysite.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 = new DateTime().toString(DateTimeFormat.forPattern("yyyy-MM-dd"));
@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;
}
}
对于robots.txt的,它看起来像下面的,很显然,你需要根据你的喜好进行配置: -
RobotsController.java
@Controller
public class RobotsController {
@RequestMapping(value = "/robots.txt", method = RequestMethod.GET)
public String getRobots(HttpServletRequest request) {
return (Arrays.asList("mysite.com", "www.mysite.com").contains(request.getServerName())) ?
"robotsAllowed" : "robotsDisallowed";
}
}
感谢漂亮的答案,我会等待点点与关闭的问题,看看是否会有更多的人贡献... –
您将需要确保这些控制方法是大量缓存。通常这些请求不应该击中应用程序服务器,而是作为apache的静态内容。 – Solubris
@Lithium也是一个好主意,你可以把它作为答案而不是聊天。无论如何,我需要动态创建我的sitemap.xml,但对于机器人来说,这应该超过必要的。 –