/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"
    },
浏览 (490)
点赞 (1)
收藏
全部评论 2
/user/profile
/user/profile
IP属地上海
AntPathMatcher antPathMatcher = new AntPathMatcher(); System.out.println(antPathMatcher.match(&#34;permission/test/{id}/test/{age}/{name}&#34;,&#34;permission/test/1/test/30/zhangsan&#34;+1));; PathPatternParser parser = new PathPatternParser(); System.out.println(parser.parse(&#34;permission/test/{id}/test/{age}/{name}&#34;).matches(PathContainer.parsePath(&#34;permission/test/1/test/30/zhangsan&#34; + 1))); 参考: https://www.cnblogs.com/zhangshiwen/p/17197684.html
点赞1
评论
/user/profile
/user/profile
IP属地上海
@Autowired private WebApplicationContext applicationContext;
点赞2
评论