乐趣区

关于springboot:SpringBoot获取所有的url路径

自己在做权限管制时会须要捕捉到所有 url,其中会因为须要申请类型,过滤了一些无申请类型的 url,话不多说,上码。

Configuration
@Slf4j
public class RolePolicyConfig {

    private final WebApplicationContext context;


    @Autowired
    public RolePolicyConfig(WebApplicationContext context) {this.context = context;}


    @PostConstruct
    public void methodInit() {
        // 获取
        RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
        // 获取 url 与类和办法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        // 初始化 map 汇合
        List<Map<String, String>> listMap = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {Map<String, String> initMap = new HashMap<>();
            RequestMappingInfo info = entry.getKey();
            // 申请类型
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            // 申请 url
            PatternsRequestCondition pattern = info.getPatternsCondition();
            // 如果类型不为空则获取
            Set<RequestMethod> methods = methodsCondition.getMethods();
            if (!ObjectUtils.isEmpty(pattern) && !CollectionUtils.isEmpty(methods)) {if (!CollectionUtils.isEmpty(pattern.getPatterns())) {log.info("办法名:{}", entry.getValue().getMethod().getName());
                    Set<String> patterns = pattern.getPatterns();
                    log.info("获取 url:{}", patterns.toString());
                    for (String url : patterns) {initMap.put("url", url);
                        initMap.put("name", url.replaceAll("/", "_").substring(1));
                    }
                    for (RequestMethod requestMethod : methods) {initMap.put("type", requestMethod.toString());
                    }
                }
                listMap.add(initMap);
            }
        }
        log.info("获取所有 url:{}", JSON.toJSONString(listMap));
    }

}
退出移动版