/user/profile
发布于

springboot 获取请求映射路径(url)

springboot 获取请求映射路径(url)

//todo 用途
代码
    public void t4() {

        // 获取springmvc处理器映射器组件对象 RequestMappingHandlerMapping无法直接注入
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, Object> mapone = new HashMap<String, Object>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            // 获取url
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                mapone.put("url", url);
            }
            // 反射获取url对应类名和方法名
            mapone.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            mapone.put("method", method.getMethod().getName()); // 方法名

            // 获取请求类型
            RequestMethodsRequestCondition methodsRequestCondition = info.getMethodsCondition();
            List<String> requestMethodList = new LinkedList<>();
            for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
                requestMethodList.add(requestMethod.toString());
            }
            mapone.put("type", requestMethodList);
            list.add(mapone);
        }
        System.out.println(JSONUtil.toJsonPrettyStr(list));
    }

输出结果:

    {
        "method": "t1",
        "className": "com.xxx.controller.TempController",
        "type": [
            "GET",
            "POST"
        ],
        "url": "/test/t1"
    },
    {
        "method": "t2",
        "className": "com.xxx.controller.TempController",
        "type": [
        ],
        "url": "/test/t2"
    },
浏览 (68)
点赞
收藏
评论