栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Spring MVC服务sitemap.xml和robots.txt

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring MVC服务sitemap.xml和robots.txt

我依靠JAXB为我生成sitemap.xml。

我的控制器如下所示,并且我有一些数据库表来跟踪要显示在站点地图中的链接:-

SitemapController.java

@Controllerpublic 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

@Controllerpublic 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";    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430535.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号