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