Can I get all of requestMapping URL with GET metho

2019-08-15 19:36发布

问题:

I want to make a sitemap.xml file dynamically. If then I need to get all of url address in the controller, How can I resolve this kinds of thing?

All I want to do is to generate sitemap.xml with spring.

The sitemap.xml have all the url that a search engine should crawl on my site and that's why I need this solution.

回答1:

Following code extracts all RequestMappingInfo instances from type and method-level @RequestMapping annotations in @Controller classes.

// 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());
        }
    }
}

You probably need to filter out mappings for the error-pages. The RequestMappingInfo object contains all the relevant mapping information that you define over @RequestMapping annotations such as:

  • RequestMappingInfo.getMethods() -> @RequestMapping(method=RequestMethod.GET)
  • RequestMappingInfo.getPatternsCondition().getPatterns() -> @RequestMapping(value = "/foo")
  • etc. for more details see RequestMappingInfo

To further catch eg. ViewController configurations as well, you need to filter for the SimpleUrlHandlerMapping type:

Map<String, SimpleUrlHandlerMapping> matchingUrlHandlerMappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
            SimpleUrlHandlerMapping.class, true, false);
SimpleUrlHandlerMapping mappings = matchingUrlHandlerMappingBeans.get("viewControllerHandlerMapping");
System.out.println(mappings.getUrlMap());