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

Java技术栈

共 1774字,需浏览 4分钟

 · 2021-10-29

点击关注公众号,Java干货及时送达

方法一

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

方法二

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

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

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

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

这种方法还是不太方便,推荐一个 Spring Boot 基础教程及实战示例:https://www.javastack.cn/categories/Spring-Boot/

方法三

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

@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。另外,关注公众号Java技术栈,在后台回复:面试,可以获取我整理的 Java、Spring 系列面试题和答案,非常齐全。

原文链接:https://blog.csdn.net/howroad/article/details/80220320

版权声明:本文为CSDN博主「howroad」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。





关注Java技术栈看更多干货



获取 Spring Boot 实战笔记!
浏览 60
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报