Springboot gets all URL paths

Time:2021-7-30

I need to capture all URLs when I do permission control. Because I need the request type, I filter some URLs without request type. I don’t say much and code them.

Configuration
@Slf4j
public class RolePolicyConfig {

    private final WebApplicationContext context;


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


    @PostConstruct
    public void methodInit() {
        //Get
        RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
        //Geturl与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        //Initialize map collection
        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();
            //Request type
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            //Request URL
            PatternsRequestCondition pattern = info.getPatternsCondition();
            //If the type is not empty, get
            Set<RequestMethod> methods = methodsCondition.getMethods();
            if (!ObjectUtils.isEmpty(pattern) && !CollectionUtils.isEmpty(methods)) {
                if (!CollectionUtils.isEmpty(pattern.getPatterns())) {
                    Log.info ("method name: {}", entry. Getvalue(). Getmethod(). Getname());
                    Set<String> patterns = pattern.getPatterns();
                    Log. Info ("get 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 ("get all URLs: {}", json.tojsonstring (listmap));
    }

}

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]