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));
    }

}
相關文章
相關標籤/搜索