SpringMVC项目中获取所有URL到Controller Method的映射

Spring是一个很好很强大的开源框架,它就像是一个容器,为我们提供了各种Bean组件和服务。对于MVC这部分而言,它里面实现了从Url请求映射控制器方法的逻辑处理,在我们平时的开发工作中并不需要太多的理会这个Url是怎么和控制器中的方法建立映射的,一切都由Spring MVC帮我们搞定了。

但是我今天在做SDK工程的时候,突然产生一个想法:能否把我项目中的所有Url和Method的映射信息打印出来?以便我一眼就看出我已经完成了那些API接口开发,这些方法需要什么参数。就像下图所示:

有了想法就要用行动,第一步肯定是要去看看别人是否已经解决了这个问题啦。查了半天的资料,倒是发现有几个相似的问题,但都没有满意的答案,只好自己调试Spring,跟踪它的处理步骤,终于让我发现了一个可行的办法,不多说,直接贴代码:

1、首先建立一个类来保存我想要的东东

private 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;

        }
    }

2、然后就是收集信息创建对象啦

@RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request)
    {
        ServletContext servletContext = request.getSession().getServletContext();
        if (servletContext == null)
        {
            return null;
        }
        WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        //请求url和处理方法的映射
        List<RequestToMethodItem> requestToMethodItemList = new ArrayList<RequestToMethodItem>();
        //获取所有的RequestMapping
        Map<String, HandlerMapping> allRequestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(appContext, 
HandlerMapping.class, true, false);

        for (HandlerMapping handlerMapping : allRequestMappings.values())
        {
            //本项目只需要RequestMappingHandlerMapping中的URL映射
            if (handlerMapping instanceof RequestMappingHandlerMapping)
            {
                RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) handlerMapping;
                Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
                for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet())
                {
                    RequestMappingInfo requestMappingInfo = requestMappingInfoHandlerMethodEntry.getKey();
                    HandlerMethod mappingInfoValue = requestMappingInfoHandlerMethodEntry.getValue();

                    RequestMethodsRequestCondition methodCondition = requestMappingInfo.getMethodsCondition();
                    String requestType = SetUtils.first(methodCondition.getMethods()).name();

                    PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
                    String requestUrl = SetUtils.first(patternsCondition.getPatterns());

                    String controllerName = mappingInfoValue.getBeanType().toString();
                    String requestMethodName = mappingInfoValue.getMethod().getName();
                    Class<?>[] methodParamTypes = mappingInfoValue.getMethod().getParameterTypes();
                    RequestToMethodItem item = new RequestToMethodItem(requestUrl, requestType, controllerName, requestMethodName, 
methodParamTypes);

                    requestToMethodItemList.add(item);
                }
                break;
            }
        }
        return new ModelAndView("index").addObject("MethodList", requestToMethodItemList);
    }

这一步我需要说明一下,我这里只用了“RequestMappingHandlerMapping”中的映射信息,其实还有另外三个HandlerMapping,如果想要获取项目中所有的映射信息,肯定是一个都不能放过了。调试的 信息如下:

3、取到数据后就展示呗,借助Thymeleaf,很容易就实现了展示,效果就是第一张图。

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Spring Thyme Seed Starter Manager</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" type="text/css" media="all" href="../../css/stsm.css" th:href="@{/css/stsm.css}"/>
    <title>请求方法列表</title>
</head>

<body>
<div style="margin: 0;padding: 0;text-align: center"><h1>请求方法列表</h1></div>
<div>
    <ul>
        <li th:each="method:${MethodList}">
            <h3 th:text="${method.methodName}"></h3>

            <p th:text="‘所属控制器:‘+${method.controllerName}"></p>

            <p th:text="‘请求URL:‘+${method.requestUrl}"></p>

            <p th:text="‘请求方式:‘+${method.requestType}"></p>

            <div>
                <p>方法参数列表:</p>
                <ul>
                    <li th:each="param:${method.methodParmaTypes}">
                        <p th:text="${param}"></p>
                    </li>
                </ul>
            </div>

        </li>
    </ul>
</div>

</body>
</html>

时间: 2024-08-02 11:02:36

SpringMVC项目中获取所有URL到Controller Method的映射的相关文章

如何在ASP.NET MVC 中获取当前URL、controller、action

一.URL的获取很简单,ASP.NET通用: [1]获取 完整url (协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取 虚拟目录名+页面名+参数: string url=Request.RawUrl;(或 string url=Request.Url.PathAndQuery;) [3]获取 虚拟目录名+页面名:string url=HttpContext.Current.Request.Url.AbsolutePath

在ASP.NET MVC 中获取当前URL、controller、action

一.URL的获取很简单,ASP.NET通用: [1]获取 完整url (协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取 虚拟目录名+页面名+参数: string url=Request.RawUrl; (或 string url=Request.Url.PathAndQuery;) [3]获取 虚拟目录名+页面名: string url=HttpContext.Current.Request.Url.AbsolutePa

在ASP.NET MVC 中获取当前URL、controller、action 、参数

URL的获取很简单,ASP.NET通用:[1]获取 完整url (协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取 虚拟目录名+页面名+参数: string url=Request.RawUrl;(或 string url=Request.Url.PathAndQuery;) [3]获取 虚拟目录名+页面名:string url=HttpContext.Current.Request.Url.AbsolutePath;(或

在ASP.NET MVC 中获取当前URL、controller、action(转)

原博:http://www.cnblogs.com/zgqys1980/archive/2012/08/01/2618152.html URL的获取很简单,ASP.NET通用:[1]获取 完整url (协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取 虚拟目录名+页面名+参数: string url=Request.RawUrl;(或 string url=Request.Url.PathAndQuery;) [3]获取 

Django自动获取项目中的全部URL

from django.utils.module_loading import import_string from django.conf import settings # for django 1.0 # from django.urls import RegexURLResolver, RegexURLPattern # for django 2.0 from django.urls.resolvers import URLResolver, URLPattern def recursi

SpringMvc项目中使用GoogleKaptcha 生成验证码

SpringMvc项目中使用GoogleKaptcha 生成验证码 前言:google captcha 是google生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比. 1.jar包准备 官方提供的pom应该是 <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</arti

项目记录:spring+springmvc 项目中 @Transactional 失效的解决方法

第一步,修改spring的配置文件和springmvc的配置文件 --------------------------------applicationContext.xml <context:annotation-config/>  <context:component-scan base-package="com.xxx"> <context:exclude-filter type="annotation" expression=&

SpringMVC项目中中文字符乱码问题及解决办法总结(非专业最优解决办法) -- ajax传值乱码; request.getParameter()乱码;

情况一: ajax中传值时是乱码(后台可以获取到中文字符,但用@ResponseBody返回时前台为乱码) 情况二: Controller 中 request.getParameter()获取到的是乱码 @RequestMapping(params = "method=submit") public String submit(HttpServletRequest request, ModelMap modelMap) throws Exception{ String uname =

javascript中获取标准URL的参数

/** * 获取标准URL的参数 * @_key:字符串,不支持数组参数(多个相同的key) * @_url:字符串,(window).location.href,使用时别误传入非window对象 * @_spliter:字符串,参数间分隔符 * 注意: * 1.如不存在指定键,返回空字符串,方便直接显示,使用时注意判断 * 2.非标准URL勿用 * 3.query(?)与hash(#)中存在键值一样时,以数组返回 */ function getUrlParams(_key, _url, _sp