2019独角兽企业重金招聘Python工程师标准>>>

@RequestMapping(value = "getUrlMapping") public ModelAndView  getUrlMapping(HttpServletRequest request) {WebApplicationContext wc = getWebApplicationContext(request.getSession().getServletContext());RequestMappingHandlerMapping rmhp = (RequestMappingHandlerMapping)wc.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0");Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods(); for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator.hasNext();) {RequestMappingInfo info = iterator.next();System.out.print(info.getConsumesCondition());System.out.print(info.getCustomCondition());System.out.print(info.getHeadersCondition());System.out.print(info.getMethodsCondition());System.out.print(info.getParamsCondition());System.out.print(info.getPatternsCondition());System.out.print(info.getProducesCondition());System.out.print("===");HandlerMethod method = map.get(info);System.out.print(method.getMethod().getName() + "--");System.out.print(method.getMethodAnnotation(RequestMapping.class).params()[0]);System.out.println();} return null;
} public WebApplicationContext getWebApplicationContext(ServletContext sc) { return WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
}

代码如上:

需要注意的是

RequestMappingHandlerMapping rmhp = (RequestMappingHandlerMapping)wc.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0");

取RequestMappingHandlerMapping 的时候,如果集成了多个展示方式的话,RequestMappingHandlerMapping 对象会有多个,直接通过class是娶不到的。但是可以通过上面的方式获取到。

package com.wy.controller.system;import com.wy.util.JsonHelper;
import com.wy.vo.BaseForm;
import com.wy.vo.system.RequestToMethodItem;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
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 org.springframework.web.servlet.support.RequestContextUtils;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.*;/*** 用户Controller*/
@Controller
@RequestMapping("/sandbox")
public class SandboxController {private static final Logger LOGGER = Logger.getLogger(SandboxController.class);@RequestMapping("/index")public ModelAndView index(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, NotFoundException {ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());RequestMappingHandlerMapping handlerMapping = (RequestMappingHandlerMapping) ac.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#1");List<RequestToMethodItem> requestToMethodItemList = loadRequestToMethodItem(handlerMapping);Map<String, Object> results = new HashMap<String, Object>();results.put("data", requestToMethodItemList);//生成jsonfor (RequestToMethodItem item:requestToMethodItemList){String url=item.getRequestUrl();String[] urls=url.split("//");}return new ModelAndView("/sandbox/index", results);}private List<RequestToMethodItem> loadRequestToMethodItem(RequestMappingHandlerMapping handlerMapping) {List<RequestToMethodItem> requestToMethodItemList = new ArrayList<RequestToMethodItem>();Map<RequestMappingInfo, HandlerMethod> map = handlerMapping.getHandlerMethods();for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {RequestMappingInfo requestMappingInfo = m.getKey();HandlerMethod mappingInfoValue = m.getValue();RequestMethodsRequestCondition methodCondition = requestMappingInfo.getMethodsCondition();int methodsSize = requestMappingInfo.getMethodsCondition().getMethods().size();String requestType = methodsSize == 0 ? "GET" : methodCondition.getMethods().toString();String requestUrl = requestMappingInfo.getPatternsCondition().toString();String controllerName = mappingInfoValue.getBeanType().toString();String requestMethodName = mappingInfoValue.getMethod().getName();Class<?>[] methodParamTypes = mappingInfoValue.getMethod().getParameterTypes();Map methodParam = loadMethodParam(requestMappingInfo, mappingInfoValue);RequestToMethodItem item = new RequestToMethodItem(requestUrl, requestType, controllerName, requestMethodName, methodParamTypes, methodParam);requestToMethodItemList.add(item);}return requestToMethodItemList;}private Map loadMethodParam(RequestMappingInfo requestMappingInfo, HandlerMethod mappingInfoValue) {try {String controllerName = mappingInfoValue.getBeanType().getName();String requestMethodName = mappingInfoValue.getMethod().getName();return getMethodParamNames2(controllerName, requestMethodName);} catch (Exception e) {e.printStackTrace();}return null;}public Map getMethodParamNames2(String clazzName, String method) throws NotFoundException, ClassNotFoundException {Map map = new HashMap();ClassPool pool = ClassPool.getDefault();pool.insertClassPath(new ClassClassPath(this.getClass()));CtClass cc = pool.get(clazzName);CtMethod cm = cc.getDeclaredMethod(method);CtClass[] parameterTypes = cm.getParameterTypes();MethodInfo methodInfo = cm.getMethodInfo();CodeAttribute codeAttribute = methodInfo.getCodeAttribute();LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);if (attr == null)throw new RuntimeException(cc.getName());String[] paramNames = new String[cm.getParameterTypes().length];int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;for (int i = 0; i < paramNames.length; i++) {paramNames[i] = attr.variableName(i + pos);String name = attr.variableName(i + pos);Class c = Class.forName(parameterTypes[i].getName());Class superClass = c.getSuperclass();if (null != superClass) {if (BaseForm.class.getName().equals(c.getSuperclass().getName())) {Map<String, String> map2 = getClassFields(c, true);map.putAll(map2);continue;}}if (HttpServletRequest.class.getName().equals(c.getName())) {continue;}if (HttpServletResponse.class.getName().equals(c.getName())) {continue;}if (BindingResult.class.getName().equals(c.getName())) {continue;}if (BaseForm.class.getName().equals(c.getName())) {Map<String, String> map2 = getClassFields(BaseForm.class, false);map.putAll(map2);continue;}map.put(name, parameterTypes[i].getSimpleName());}return map;}/*** 获取类实例的属性值** @param clazz              类名* @param includeParentClass 是否包括父类的属性值* @return 类名.属性名=属性类型*/public static Map<String, String> getClassFields(Class clazz, boolean includeParentClass) {Map<String, String> map = new HashMap<String, String>();Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {map.put(field.getName(), field.getType().getSimpleName());}if (includeParentClass)getParentClassFields(map, clazz.getSuperclass());return map;}/*** 获取类实例的父类的属性值** @param map   类实例的属性值Map* @param clazz 类名* @return 类名.属性名=属性类型*/private static Map<String, String> getParentClassFields(Map<String, String> map, Class clazz) {Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {map.put(field.getName(), field.getType().getSimpleName());}if (clazz.getSuperclass() == null) {return map;}//getParentClassFields ( map, clazz.getSuperclass ( ) );return map;}}

转载于:https://my.oschina.net/u/557580/blog/534699

获取springmvc中所有的Controller相关推荐

  1. springmvc 中controller与jsp传值

    在springmvc中的controller所对应的函数中,如果需要从*.jsp页面中获取数据,可以自行在函数括号中写,springmvc会自动封装传过来的. spring-mvc.xml <! ...

  2. 前端js获取SpringMvc后台model中传值

    也许你迷茫,但是我想说,在你迷茫的同时,保持本心,过好今天就好. 使用 SpringBoot +SpringMVC +thymeleaf 组合实现的功能,期望在 thymeleaf 中的html中的j ...

  3. SpringMVC无法获取请求中的参数的问题的调查与解决(1)

    SpringMVC无法获取请求中的参数的问题的调查与解决(1) 参考文章: (1)SpringMVC无法获取请求中的参数的问题的调查与解决(1) (2)https://www.cnblogs.com/ ...

  4. SpringMVC中,前台jsp封装参数,绑定参数,传递参数到后台controller的过程详解

    前台到后台的流程:前台jsp->后台:controller控制器层->service业务层->DAO数据访问层->数据库model模型层. 从上面流程可知,前台jsp的数据,想 ...

  5. springmvc中Controller方法的返回值

    1.1 返回ModelAndView controller方法中定义ModelAndView对象并返回,对象中可添加model数据.指定view. 1.2 返回void 在controller方法形参 ...

  6. 详解SpringMVC中Controller的方法中参数的工作原理[附带源码分析]

    目录 前言 现象 源码分析 HandlerMethodArgumentResolver与HandlerMethodReturnValueHandler接口介绍 HandlerMethodArgumen ...

  7. 详解SpringMVC中Controller的方法中参数的工作原理[附带源码分析] good

    目录 前言 现象 源码分析 HandlerMethodArgumentResolver与HandlerMethodReturnValueHandler接口介绍 HandlerMethodArgumen ...

  8. 解决springmvc中添加了静态资源访问路径之后就访问不到Controller路径的问题

    访问不到Controller,也访问不到controller路径. Controller代码: /*** Created by 李柏霖* 2020/10/19 17:35*/package com.l ...

  9. .net mvc 获取url中controller和action

    第一种: 获取controller名称:ViewContext.RouteData.Values["controller"] 获取action名称:ViewContext.Rout ...

最新文章

  1. c语言求占用内存sizeof,C语言中sizeof的用法
  2. Struts2 ognl表达式
  3. [Java]将二叉树的左右子树交换 非递归实现
  4. 通过Java编写一个服务器理解动态Web,静态Web
  5. 信息设计中的“父子关系”
  6. HDOJ 2013 蟠桃记
  7. 【sklearn第十三讲】Naive Bayes分类器
  8. 模拟人生4极乐净土mod_如何在《模拟人生4》中下载Mod
  9. 在线全网音乐搭建源码_支持下载
  10. python找不到解释器_为什么pycharm找不到python解释器
  11. andriod studio 自带模拟器设置开发者模式
  12. Flume1.6.0之Error-protobuf-This is supposed to be overridden by subclasses
  13. 阿兹尔海默症生物标志物(姑且叫标志物)的一些总结
  14. 最新官方新浪短网址API接口分享-附代码调用演示
  15. 线段树+思维 Codeforces Round #197 (Div. 2) D题 Xenia and Bit Operations
  16. 剑指Offer(二):替换空格
  17. Arcface中的IR_SE模块
  18. 大数据学习第一课:虚拟机安装配置
  19. 微服务启动成功无法注册到服务注册中心
  20. STM32GPIO寄存器CRL、CRH、IDR、ODR、BSRR、BRR

热门文章

  1. 高校计算机实验室管理制度,高校计算机实验室管理论文
  2. 学生电脑哪个牌子好_双开门冰箱哪个牌子好 双开门冰箱什么牌子好
  3. listctrl 优化_上海SEO整站优化公司_新站整站快速排名优化
  4. linux 通过虚拟ip出路由器,linux模拟路由器实验
  5. C++安全方向openssl(二):2.2 C++代码实现base16编解码
  6. solarflare低延迟网卡_动态丨赛灵思收购solarflare,数据优先是重要布局
  7. D3 Geographies
  8. 在过程中要正式批准可交付成果_PMP模拟考试一(200题中文版)
  9. python list方法说明_对python中list的五种查找方法说明
  10. mybatis多条件批量查询_Mybatis【14】 Mybatis如何实现一对多查询?