当前位置: 移动技术网 > IT编程>开发语言>Java > 详解获取Spring MVC中所有RequestMapping以及对应方法和参数

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

  /**
   * @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,则直接引入可以使用了。

import org.apache.ibatis.javassist.*;
import org.apache.ibatis.javassist.bytecode.*;

getmethodparams 的实现如下:

/**
   * @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,代码如下:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网