服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解获取Spring MVC中所有RequestMapping以及对应方法和参数

详解获取Spring MVC中所有RequestMapping以及对应方法和参数

2020-08-29 11:40Y橡树Y Java教程

本篇文章主要介绍了详解获取Spring MVC中所有RequestMapping以及对应方法和参数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

Spring MVC中想要对每一个URL进行权限控制,不想手工整理这样会有遗漏,所以就动手写程序了。代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * @return
 * @author Elwin ZHANG
 * 创建时间:2017年3月8日 上午11:48:22
 * 功能:返回系统中的所有控制器映射路径,以及对应的方法
 */
@RequestMapping(value = "/maps", produces = "application/json; charset=utf-8")
@ResponseBody
public Object getMapPaths(){
  String result="";
   RequestMappingHandlerMapping rmhp = springHelper.getObject(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
    for(RequestMappingInfo info : map.keySet()){
      result +=info.getPatternsCondition().toString().replace("[", "").replace("]", "")+ "\t"   ;
      HandlerMethod hm=map.get(info);
      result +=hm.getBeanType().getName()+ "\t"   ;
      result +=getMethodParams(hm.getBeanType().getName(),hm.getMethod().getName())+ "\t";
      result +=info.getProducesCondition().toString().replace("[", "").replace("]", "")+ "\t"   ;
      result += "\r\n";
    }
  return result;
}

getMethodParams是专门用于获取方法中参数名称的函数,因为用Java自身的反射功能是获取不到的,浪费我不少时间,后来网上看到JBOSS的JAVAssist类可以。其实这个JAVAssist类库也被封装在Mybatis中,如果系统使用了Mybatis,则直接引入可以使用了。

?
1
2
import org.apache.ibatis.javassist.*;
import org.apache.ibatis.javassist.bytecode.*;

getMethodParams 的实现如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
   * @param className 类名
   * @param methodName 方法名
   * @return 该方法的声明部分
   * @author Elwin ZHANG
   * 创建时间:2017年3月8日 上午11:47:16
   * 功能:返回一个方法的声明部分,包括参数类型和参数名
   */
  private String getMethodParams(String className,String methodName){
    String result="";
    try{
      ClassPool pool=ClassPool.getDefault();
       ClassClassPath classPath = new ClassClassPath(this.getClass());
       pool.insertClassPath(classPath);
      CtMethod cm =pool.getMethod(className, methodName);
     // 使用javaassist的反射方法获取方法的参数名
      MethodInfo methodInfo = cm.getMethodInfo();
      CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
      LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
      result=cm.getName() + "(";
      if (attr == null) {
        return result + ")";
      }
      CtClass[] pTypes=cm.getParameterTypes();
      String[] paramNames = new String[pTypes.length];
      int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
      for (int i = 0; i < paramNames.length; i++) {
        if(!pTypes[i].getSimpleName().startsWith("HttpServletRe")){
          result += pTypes[i].getSimpleName();
          paramNames[i] = attr.variableName(i + pos);
          result += " " + paramNames[i]+",";
        }
      }
      if(result.endsWith(",")){
        result=result.substring(0, result.length()-1);
      }
      result+=")";
    }catch(Exception e){
      e.printStackTrace();
    }
    return result;
  }

这样就可以获得每个URL路径与期对应的方法声明了。

另外SpringHelper是自己封装的Spring工具类,可以用来直接获取Spring管理的Bean,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
 
/**
 * @author Elwin ZHANG
 * 创建时间:2016年4月14日 上午9:12:13
 * 功能:Spring 工具类,用于获取Spring管理的Bean
 */
@Component
public class SpringHelper implements ApplicationContextAware {
  // 日志输出类
  private static Logger logger = Logger.getLogger(SpringHelper.class);
 
  // 当前的Spring上下文
  private static ApplicationContext applicationContext;
 
  @Override
  public void setApplicationContext(ApplicationContext arg0)
      throws BeansException {
    applicationContext = arg0;
  }
 
  /**
   * @param beanName bean Id
   * @return 如果获取失败,则返回Null
   * @author Elwin ZHANG
   * 创建时间:2016年4月14日 上午9:52:55
   * 功能:通过BeanId获取Spring管理的对象
   */
  public Object getObject(String beanName) {
    Object object = null;
    try {
      object = applicationContext.getBean(beanName);
    } catch (Exception e) {
      logger.error(e);
    }
    return object;
  }
 
 
  /**
   * @return
   * @author Elwin ZHANG
   * 创建时间:2017年3月7日 下午3:44:38
   * 功能:获取Spring的ApplicationContext
   */
  public ApplicationContext getContext() {
    return applicationContext;
  }
 
  /**
   * @param clazz 要获取的Bean类
   * @return 如果获取失败,则返回Null
   * @author Elwin ZHANG
   * 创建时间:2016年4月14日 上午10:05:27
   * 功能:通过类获取Spring管理的对象
   */
  public <T> T getObject(Class<T> clazz) {
    try {
      return applicationContext.getBean(clazz);
    } catch (Exception e) {
      logger.error(e);
    }
    return null;
  }
 
/**
 * @param code 配置文件中消息提示的代码
 * @param locale 当前的语言环境
 * @return 当前语言对应的消息内容
 * @author Elwin ZHANG
 * 创建时间:2016年4月14日 上午10:34:25
 * 功能:获取当前语言对应的消息内容
 */
  public String getMessage(String code,Locale locale){
    String message;
    try{
      message=applicationContext.getMessage(code, null, locale);
    }catch(Exception e){
      logger.error(e);
      message="";
    }
    return message;
  }
 
  /**
   *
   * @param code 配置文件中消息提示的代码
   * @param request 当前的HTTP请求
   * @return 当前语言对应的消息内容
   * @author Elwin ZHANG
   * 创建时间:2016年4月14日 下午3:03:37
   * 功能:获取当前语言对应的消息内容
   */
  public String getMessage(String code,HttpServletRequest request){
    String message;
    try{
      message=applicationContext.getMessage(code, null, getCurrentLocale(request));
    }catch(Exception e){
      logger.error(e);
      message="zh_CN";
    }
    return message;
  }
 
  /**
   * @param request 当前的HTTP请求
   * @return 当前用户Cookie中的语言
   * @author Elwin ZHANG
   * 创建时间:2016年4月14日 下午2:59:21
   * 功能:当前用户保存Cookie中的默认语言
   */
  public Locale getCurrentLocale(HttpServletRequest request){
    return resolver.resolveLocale(request);
  }
 
  //Cookie本地语言解析器,Spring提供
  @Autowired
  CookieLocaleResolver resolver;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.jianshu.com/p/bb9e0c402341#

延伸 · 阅读

精彩推荐