Spring Boot项目URL权限控制优化指南:自动获取全部URL
在Spring Boot项目中实现URL权限控制时,手动一个一个去Controller中查找URL是费时费力的。有些权限点的命名和URL之间存在对应关系。如果能够通过程序自动获取全部URL,将能省去很多麻烦。可以按照以下步骤进行操作:
- 添加以下Controller:
@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<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; }