美文网首页
Spring Mvc获取所有注册URL

Spring Mvc获取所有注册URL

作者: 小代码 | 来源:发表于2017-09-27 14:34 被阅读0次

    废话不多说,直接上代码,以下两种方式获取SpringMVC中注册的URL。

    @Controller
    public class UrlsController {
        // 方法 1
        @ResponseBody
        @RequestMapping("/urls1")
        public Object getUrlMapping(HttpServletRequest request) {
            WebApplicationContext wc = RequestContextUtils.getWebApplicationContext(request);
            RequestMappingHandlerMapping rmhp = wc.getBean(RequestMappingHandlerMapping.class);
            Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
            List<String> urls = new ArrayList<>(map.size());
            for (RequestMappingInfo info : map.keySet()) {
                System.out.println(info.getPatternsCondition().toString() + "," + map.get(info).getBean().toString());
                urls.add(info.getPatternsCondition().toString());
            }
            return urls;
        }
    
        // 方法 2
        @Autowired
        private RequestMappingHandlerMapping handlerMapping;
    
        @ResponseBody
        @RequestMapping("/urls2")
        public Object index(Long id, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ClassNotFoundException {
            Map<RequestMappingInfo, HandlerMethod> map = this.handlerMapping.getHandlerMethods();
            List<String> urls = new ArrayList<>(map.size());
            for(Map.Entry<RequestMappingInfo, HandlerMethod> entry  : map.entrySet()) {
                System.out.println(entry.getKey() + System.lineSeparator() + entry.getValue());
                urls.add(entry.getKey().toString());
            }
            return urls;
        }
    }
    

    对了注意不能Response返回RequestMappingInfo, HandlerMethod对象,否则会报错。其他web.xml以及springmvc的配置都需要加上。

    相关文章

      网友评论

          本文标题:Spring Mvc获取所有注册URL

          本文链接:https://www.haomeiwen.com/subject/vyjuextx.html