spring boot中獲取所有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;
    }


參考http://jayung.iteye.com/blog/2240864,
https://blog.csdn.net/Clark_Lu/article/details/78670411?locationNum=7&fps=1

發佈了43 篇原創文章 · 獲贊 25 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章