Spring Boot 如何获取 Controller 方法名和注解信息

目录
文章目录隐藏
  1. 方法一
  2. 方法二
  3. 方法三

方法一

通过 request 获得用户的 URI,再逐一循环判断是否可以操作。只是这种方法很让人难受。

方法二

通过用户要访问的方法来判断是否有权限:

preHandle方法中handler实际为HandlerMethod,(看网上说的有时候不是 HandlerMethod),加个instanceof验证吧

可以得到方法名:h.getMethod().getName()

可以得到 RequestMapping 注解中的值:h.getMethodAnnotation(RequestMapping.class)

这种方法还是不太方便

方法三

自定义注解,自定义注解代码:

@Retention(RUNTIME)
@Target(METHOD)
public @interface MyOperation {
    String value() default "";//默认为空,因为名字是 value,实际操作中可以不写"value="
}

Controller 代码:

@Controller("testController")
public class TestController {
    @MyOperation("用户修改")//主要看这里
    @RequestMapping("test")
    @ResponseBody
    public String test(String id) {
        return "Hello,2018!"+id;
    }
}

拦截器的代码:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    System.out.println("进入拦截器");
    if(handler instanceof HandlerMethod) {
        HandlerMethod h = (HandlerMethod)handler;
        System.out.println("用户想执行的操作是:"+h.getMethodAnnotation(MyOperation.class).value());
        //判断后执行操作...
    }
    return HandlerInterceptor.super.preHandle(request, response, handler);
}

在每个方法上面加注解太麻烦啦,可以在类上加注解:

@Retention(RUNTIME)
@Target(TYPE)
public @interface MyOperation {
    String value() default "";
}

//拦截器中这样获得
h.getMethod().getDeclaringClass().getAnnotation(MyOperation.class);

我可以获取 requestMapping,不用创建自定义注解啊,值得注意的是,不要使用 GetMapping 等,要使用 requestMapping。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Spring Boot 如何获取 Controller 方法名和注解信息

发表回复