1. 程式人生 > >SpringMVC專案中獲取所有URL到Controller Method的對映

SpringMVC專案中獲取所有URL到Controller Method的對映

參考連結 https://www.cnblogs.com/yuananyun/archive/2014/08/25/3934371.html

 

參考上面大神的程式碼寫的,發現他的程式碼有點小小的問題啊,我這隻菜鳥有點小小不懂哈,然後我就Ctrl+C了一下,然後修改一下了啊,改成我寄己可以執行的啊,下面上程式碼

Controller程式碼

    @ResponseBody
    @RequestMapping("/url/list/show")
    public String listUrlsShow(){
        Map map =  this.handlerMapping.getHandlerMethods();
        Iterator
<?> iterator = map.entrySet().iterator(); List<RequestToMethodItem> urls=new ArrayList<>(); while(iterator.hasNext()){ Map.Entry<RequestMappingInfo, HandlerMethod> entry = (Map.Entry) iterator.next(); RequestMappingInfo requestMappingInfo
= entry.getKey(); HandlerMethod mappingInfoValue = entry.getValue(); String controllerName = mappingInfoValue.getBeanType().toString(); String requestMethodName = mappingInfoValue.getMethod().getName(); Class<?>[] methodParamTypes = mappingInfoValue.getMethod().getParameterTypes(); RequestMethodsRequestCondition methodCondition
= requestMappingInfo.getMethodsCondition(); Iterator it=methodCondition.getMethods().iterator(); String requestType =it.hasNext()?methodCondition.getMethods().iterator().next().name():""; PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition(); String requestUrl = patternsCondition.getPatterns().iterator().next(); RequestToMethodItem item = new RequestToMethodItem(requestUrl, requestType, controllerName, requestMethodName, methodParamTypes); urls.add(item); } return successResponse(urls); }

使用到的POJO程式碼:

RequestToMethodItem.java
public class RequestToMethodItem {
    public String controllerName;
    public String methodName;
    public String requestType;
    public String requestUrl;
    public Class<?>[] methodParmaTypes;

    public RequestToMethodItem(String requestUrl, String requestType, String controllerName, String requestMethodName,
                        Class<?>[] methodParmaTypes) {
        this.requestUrl = requestUrl;
        this.requestType = requestType;
        this.controllerName = controllerName;
        this.methodName = requestMethodName;
        this.methodParmaTypes = methodParmaTypes;
    }


}

好啦好啦,就這些程式碼啦,撒花~~~

說明一下哈,敲黑板,注意聽:

successResponse()方法是我自己封裝的哈,功能是把最後得到的結果List,轉換成json物件哈,反正最後結果都在urls中啦。可以選擇列印撒。。

執行一下哦,come on baby!!!  輸入連結,訪問訪問。。。

下面就是執行結果圖啦,散開散開,圖有點大鴨