springboot url中获取所有RequestMapping的URL路径列表集

spring boot 项目在做URL权限控制的时候需要获取全部的URL,一个一个去controller中找费时费力,有的权限点的命名和URL有一定的对应关系。如果能用程序获得全部URL,将会省去很多事。在项目中添加如下Controller,请求/getAllUrl,即可看到项目所有的URL。当然也可以根据项目将URL写入数据库或写入配置文件。

    @Autowired
    WebApplicationContext applicationContext;
 
    @RequestMapping(value = "v1/getAllUrl", method = RequestMethod.POST)
    public Object getAllUrl() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        
//        List<String> urlList = new ArrayList<>();
//        for (RequestMappingInfo info : map.keySet()) {
//            // 获取url的Set集合,一个方法可能对应多个url
//            Set<String> patterns = info.getPatternsCondition().getPatterns();
//
//            for (String url : patterns) {
//                urlList.add(url);
//            }
//        }
 
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();  
            HandlerMethod method = m.getValue();  
            PatternsRequestCondition p = info.getPatternsCondition();  
            for (String url : p.getPatterns()) {  
                map1.put("url", url);
            }  
            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名  
            map1.put("method", method.getMethod().getName()); // 方法名 
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }
            
            list.add(map1);
        }
 
        JSONArray jsonArray = JSONArray.fromObject(list);
 
        return jsonArray;
    }
        ApplicationContext context = event.getApplicationContext();
        
        RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            RequestMappingInfo info = m.getKey();  
            HandlerMethod method = m.getValue();  
            System.out.println("请求url:" + info.getPathPatternsCondition() );
            System.out.println("请求方式:" + info.getMethodsCondition());
            System.out.println("className:" + method.getMethod().getDeclaringClass().getName());
            System.out.println("method:" + method.getMethod().getName());
            System.out.println("===================");
        }

 


posted on 2023-01-15 18:16  Ruthless  阅读(1408)  评论(0编辑  收藏  举报