我可以在 Spring 中使用 GET 方法获取所有 requestMapping URL 吗?

Can I get all of requestMapping URL with GET method in the Spring?

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

我只想生成 sitemap.xml 和 spring。

sitemap.xml 具有搜索引擎应在我的网站上抓取的所有 url 这就是为什么我需要这个解决方案。

以下代码从 @Controller 类.

中的类型和方法级别 @RequestMapping 注释中提取所有 RequestMappingInfo 个实例
// 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());