首页 > 解决方案 > 从 url 字符串获取 HandlerMethod

问题描述

我需要知道哪个控制器会处理特定的 url。不幸的是,我没有可用的 HttpServletRequest,只有 url 作为字符串。

例如给定的网址是:https://localhost:8090/name-of-product/147/product

ProductController 有映射:@GetMapping("/{name}/{code}/product")

我想获得一些 ProductController 将处理这个 url 的信息https://localhost:8090/name-of-product/147/product

我有这样的事情:

static class CustomPathContainer implements PathContainer {

        String path;

        CustomPathContainer(String path) {
            this.path = path;
        }

        static CustomPathContainer of(String path) {
            return new CustomPathContainer(path);
        }

        @Override
        public String value() {
            return path;
        }

        @Override
        public List<Element> elements() {
            return List.of();
        }
    }
        CustomPathContainer refCustomPathContainer = CustomPathContainer.of("/name-of-product/147/product");
        // Autowired RequestMappingHandlerMapping handlerMapping
        Set<Map.Entry<RequestMappingInfo, HandlerMethod>> entries = handlerMapping.getHandlerMethods().entrySet();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> handlerMethod : entries) {
            RequestMappingInfo key = handlerMethod.getKey();
            PathPatternsRequestCondition pathPatternsCondition = key.getPathPatternsCondition();
            Set<PathPattern> patterns = pathPatternsCondition.getPatterns();
            for (PathPattern pathPattern : patterns) {
                // Some check if url and pattern match?
                PathPattern.PathMatchInfo matches = pathPattern.matchAndExtract(refCustomPathContainer);
            }
        }

标签: javaspringspring-bootspring-mvc

解决方案


推荐阅读