整合swagger后,获取项目中所有的url

        本文主要展示获取项目中url,比对是否有重复,尤其是使用路径参数,比如/m/user/{id}、/m/user/{phone}这种情况访问路径是/m/user/2;有可能被/m/user/{phone}解析到。所以获取所有的url后进行比对,查找有可能出错的代码


import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/m")
public class TestController22 {

    @Resource
    WebApplicationContext applicationContext;

    @RequestMapping(value = "/getAllURL")
    public Object getAllURL() {
        List<Map<String, String>> resultList = new ArrayList<>();

        RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
            Map<String, String> resultMap = new LinkedHashMap<>();

            RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
            HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();

            resultMap.put("className",handlerMethod.getMethod().getDeclaringClass().getName()); // 类名
            Annotation[] parentAnnotations = handlerMethod.getBeanType().getAnnotations();
            for (Annotation annotation : parentAnnotations) {
                if (annotation instanceof Api) {
                    Api api = (Api) annotation;
                    resultMap.put("classDesc",api.value());
                } else if (annotation instanceof RequestMapping) {
                    RequestMapping requestMapping = (RequestMapping) annotation;
                    if (null != requestMapping.value() && requestMapping.value().length > 0) {
                        resultMap.put("classURL",requestMapping.value()[0]);//类URL
                    }
                }
            }
            resultMap.put("methodName", handlerMethod.getMethod().getName()); // 方法名
            Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
            if (annotations != null) {
                // 处理具体的方法信息
                for (Annotation annotation : annotations) {
                    if (annotation instanceof ApiOperation) {
                        ApiOperation methodDesc = (ApiOperation) annotation;
                        String desc = methodDesc.value();
                        resultMap.put("methodDesc",desc);//接口描述
                    }
                }
            }
            PatternsRequestCondition p = requestMappingInfo.getPatternsCondition();
            for (String url : p.getPatterns()) {
                resultMap.put("methodURL",url);//请求URL
            }
            RequestMethodsRequestCondition methodsCondition = requestMappingInfo.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                resultMap.put("requestType",requestMethod.toString());//请求方式:POST/PUT/GET/DELETE
            }
            resultList.add(resultMap);
        }
        List<String> classUrl = resultList.stream().map(m -> m.get("methodURL")).collect(Collectors.toList());
        List<String> collect = classUrl.stream().sorted().collect(Collectors.toList());

//        System.out.println(collect);
//        return collect;
        //展示的信息更详细,
        return JSONArray.toJSON(resultList);
    }

下面这个代码整合swagger以后就不行了,可以自己尝试


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leading.gmstaffapi.logistics.api.rest.mobilecontroller.req.FindLogisticsDTO;
import com.leading.gmstaffapi.outapi.gm.logistics.OrderLogisticsApiClient;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.*;




 @Resource
    ConfigurableApplicationContext run;
    //获取项目所有url
    public String getAllUrl(ConfigurableApplicationContext run) {

//        LOGGER.info("getUrlMethod is called.");
//
        StringBuilder sbSql = new StringBuilder();
        sbSql.append("INSERT INTO interfacelist (url,name,type)values");

        //获取restcontroller注解的类名
        String[] beanNamesForAnnotation = run.getBeanNamesForAnnotation(RestController.class);

        //获取类对象
        for (String str : beanNamesForAnnotation) {
            Object bean = run.getBean(str);
            Class<?> forName = bean.getClass();
            System.out.println(forName.getName());

            //获取requestmapping注解的类
            RequestMapping declaredAnnotation = forName.getAnnotation(RequestMapping.class);
            Annotation[] annotations = forName.getAnnotations();
            for (Annotation annotation : annotations) {

                System.out.println(annotation);
            }

            String url_path = "";
            if (declaredAnnotation != null) {
                String[] value = (declaredAnnotation.value());
                //获取类的url路径
                url_path = value[0];
            }
            for (Method method : forName.getDeclaredMethods()) {
                RequestMapping annotation2 = method.getAnnotation(RequestMapping.class);
                if (annotation2 != null) {
                    url_path += annotation2.value()[0];
                    System.out.println("方法路径" + url_path + "方法名" + method.getName());
                    sbSql.append("('").append(url_path).append("','").append(method.getName()).append("','").append("api'),");
                }
            }
        }

        //删除字符串sbCols最后一个逗号
        sbSql.deleteCharAt(sbSql.length() - 1);

        System.out.println(sbSql);

        return sbSql.toString();
    }

参考文章: 

获取项目中所有URL--获取swagger上展示的接口信息 - 劈天造陆 - 博客园有时我们需要接口的一些基本信息,比如接口请求路径,接口请求方式等,我们用这些信息来做判断,或者入库。 我在开发接口权限的时候就遇到了这个问题,之前写的接口很多,现在需要将这些接口信息存到数据库中, 用https://www.cnblogs.com/java-spring/p/10838514.html

这篇文章是没有整合swagger的,整合之后代码就获取不到了

SpringMVC项目中获取所有URL到Controller Method的映射 - 流水殇 - 博客园Spring是一个很好很强大的开源框架,它就像是一个容器,为我们提供了各种Bean组件和服务。对于MVC这部分而言,它里面实现了从Url请求映射控制器方法的逻辑处理,在我们平时的开发工作中并不需要太多https://www.cnblogs.com/yuananyun/p/3934371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值