【问题标题】:Can I get all of requestMapping URL with GET method in the Spring?我可以在 Spring 中使用 GET 方法获取所有 requestMapping URL 吗?
【发布时间】:2016-03-19 13:18:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring url get sitemap sitemap.xml


    【解决方案1】:

    以下代码从@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());
    

    【讨论】:

    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多