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 map = mapping.getHandlerMethods();
        // 初始化map集合
        List> listMap = new ArrayList<>();
        for (Map.Entry entry : map.entrySet()) {
            Map initMap = new HashMap<>();
            RequestMappingInfo info = entry.getKey();
            // 请求类型
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            // 请求url
            PatternsRequestCondition pattern = info.getPatternsCondition();
            // 如果类型不为空则获取
            Set methods = methodsCondition.getMethods();
            if (!ObjectUtils.isEmpty(pattern) && !CollectionUtils.isEmpty(methods)) {
                if (!CollectionUtils.isEmpty(pattern.getPatterns())) {
                    log.info("方法名:{}", entry.getValue().getMethod().getName());
                    Set 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));
    }

}

你可能感兴趣的:(SpringBoot获取所有的url路径)