方法一
通過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="https://www.cnblogs.com/javastack/p/}
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,
原文鏈接:https://blog.csdn.net/howroad/article/details/80220320
著作權宣告:本文為CSDN博主「howroad」的原創文章,遵循CC 4.0 BY-SA著作權協議,轉載請附上原文出處鏈接及本宣告,
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2021最新版)
2.別在再滿屏的 if/ else 了,試試策略模式,真香!!
3.臥槽!Java 中的 xx ≠ null 是什么新語法?
4.Spring Boot 2.5 重磅發布,黑暗模式太炸了!
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/342996.html
標籤:Java
