1

我想动态地制作一个 sitemap.xml 文件。如果那时我需要获取控制器中的所有 url 地址,我该如何解决这种事情?

我想做的就是用spring生成sitemap.xml。

sitemap.xml 包含搜索引擎应该在我的网站上抓取的所有 url,这就是我需要这个解决方案的原因。

4

1 回答 1

2

以下代码RequestMappingInfo从类中的类型和方法级别@RequestMapping注释中提取所有实例@Controller

// context = ApplicationContext
Map<String, RequestMappingHandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
    RequestMappingHandlerMapping.class, true, false);

if (!matchingBeans.isEmpty()) {
    ArrayList<HandlerMapping> handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
    AnnotationAwareOrderComparator.sort(handlerMappings);

    RequestMappingHandlerMapping mappings = matchingBeans.get("requestMappingHandlerMapping");
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mappings.getHandlerMethods();

    for (RequestMappingInfo requestMappingInfo : handlerMethods.keySet()) {
        RequestMethodsRequestCondition methods = requestMappingInfo.getMethodsCondition();

        // Get all requestMappingInfos with 
        //  1) default request-method (which is none) 
        //  2) or method=GET
        if (methods.getMethods().isEmpty() || methods.getMethods().contains(RequestMethod.GET)) {
            System.out.println(requestMappingInfo.getPatternsCondition().getPatterns() + " -> produces " +
                    requestMappingInfo.getProducesCondition());
        }
    }
}

您可能需要过滤掉错误页面的映射。该RequestMappingInfo对象包含您通过@RequestMapping注释定义的所有相关映射信息,例如:

  • RequestMappingInfo.getMethods()->@RequestMapping(method=RequestMethod.GET)
  • RequestMappingInfo.getPatternsCondition().getPatterns()->@RequestMapping(value = "/foo")
  • 等有关更多详细信息,请参阅RequestMappingInfo

进一步捕捉例如。ViewController配置也是如此,您需要过滤SimpleUrlHandlerMapping类型:

Map<String, SimpleUrlHandlerMapping> matchingUrlHandlerMappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
            SimpleUrlHandlerMapping.class, true, false);
SimpleUrlHandlerMapping mappings = matchingUrlHandlerMappingBeans.get("viewControllerHandlerMapping");
System.out.println(mappings.getUrlMap());
于 2016-03-19T14:18:20.587 回答