如何使用攔截器獲取 Controller 方法名和註解信息?

源 /CSDN         文 / howroad

在使用 SpringMVC 進行項目的時候用到了權限驗證。

表分爲:

用戶 - 角色 - 資源都是多對多的關係,驗證無非就是收到請求後,在攔截器循環判斷用戶是否有權限執行操作。

方法一:通過 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

作者 | howroad 

來源 | https://blog.csdn.net/howroad/article/details/80220320

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/AMsV30MjDp165ssreE90Tg