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

ぃ、小莉子 提交于 2019-12-11 14:12:21

问题


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


来源:https://stackoverflow.com/questions/36102231/can-i-get-all-of-requestmapping-url-with-get-method-in-the-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!