本人在做权限控制时会需要捕捉到所有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));
    }

}

Zeran
32 声望4 粉丝

学而不思则罔,思而不学则殆。