栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何获取SpringMVC应用中的所有映射信息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何获取SpringMVC应用中的所有映射信息

我们知道,一般的SpringMVC应用都是采用RequestMappingHandlerMapping通过RequestMapping完成URL与方法映射。RequestMappingHandlerMapping是保存在容器中的。那么如果我们想获取相关信息,可以从容器中获取RequestMappingHandlerMapping从而得到相关信息。
如下代码展示了:
首先定义JavaBean来保存需要获取的信息

static class MappingInfo{
        private Class className; //类
        private Method method;//方法
        private List httpMethods;//http方法,同一个接口可以通过GET/POST访问
        private List classRequestMappings;//class定义的映射
        private List requestMappings;//具体的每个映射,不包含context-path,但是包含类上的

然后从容器中获取RequestMappingHandlerMapping,当然容器你可以通过ApplicationContextAware注入或者@Autowired注入

RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map map = mapping.getHandlerMethods();

        List list = new ArrayList<>(map.size());

        for (Map.Entry m : map.entrySet()) {
            MappingInfo mappingInfo = new MappingInfo();
            RequestMappingInfo info = m.getKey();
            HandlerMethod handlerMethod = m.getValue();
            //获取当前方法所在类名
            Class bean = handlerMethod.getBeanType();
            //使用反射获取当前类注解内容
            RequestMapping requestMapping = bean.getAnnotation(RequestMapping.class);
            if(null != requestMapping){
                String[] value = (String[]) AnnotationUtils.getAnnotationAttributes(requestMapping).get("value");
                mappingInfo.setClassRequestMappings(Arrays.asList(value));
            }
            //获取方法上注解以及注解值

            PatternsRequestCondition p = info.getPatternsCondition();
            List urls = new ArrayList<>();
            urls.addAll(p.getPatterns());
            mappingInfo.setRequestMappings(urls);

            mappingInfo.setClassName(handlerMethod.getMethod().getDeclaringClass());
            mappingInfo.setMethod(handlerMethod.getMethod());
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();

            List httpMethods = new ArrayList<>();
            methodsCondition.getMethods().forEach(requestMethod -> httpMethods.add(requestMethod.toString()));
            mappingInfo.setHttpMethods(httpMethods);

            list.add(mappingInfo);
        }

        System.out.println(JSON.toJSONString(list));
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915440.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号