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

猜你喜欢

转载自blog.csdn.net/tt____tt/article/details/82012999