我想动态制作一个sitemap.xml文件。 如果那时我需要在控制器中获取所有url地址, 我该如何解决这类问题?
我想做的就是用spring生成sitemap.xml。
sitemap.xml包含搜索引擎应在我的网站上抓取的所有网址 这就是我需要这个解决方案的原因。
答案 0 :(得分: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()
- &gt; @RequestMapping(method=RequestMethod.GET)
RequestMappingInfo.getPatternsCondition().getPatterns()
- &gt; @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());