前言
我以验证角色权限注解为例 @PreAuth
代码
1.注解
//这里的参数是一个数组,可以对类、方法、构造器、属性等等生效,这里我只写了方法 @Target(ElementType.METHOD) //运行时生效 @Retention(RetentionPolicy.RUNTIME) public @interface PreAuth { //注解的值 String value(); }
2.方法上使用
@RestController @RequestMapping("/test") public class UserController { @GetMapping("/{id}") @PreAuth(value = "111") public String test(@PathVariable String id) { return "id=" + id; } }
3. 拦截器
public class AnnotationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //强转为HandlerMethod HandlerMethod handlerMethod = (HandlerMethod) handler; //获取注解 PreAuth preAuth = handlerMethod.getMethodAnnotation(PreAuth.class); //获取注解值, String value = preAuth.value(); /* 进行逻辑处理, 如权限认证 */ //获取用户的角色权限,判断是否拥有权限,拥有就放行 // 这里我就不多写了,因为每个项目的需求都是不一样的,可以根据自己的需求进行编写 return false; } }
4.注册拦截器
public class AnnotationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { /** * 这里给不是处理方法的拦截进行放行,否则会拦截一些静态的资源,导致执行多次拦截方法 */ if (!(handler instanceof HandlerMethod)) return true; //强转为HandlerMethod HandlerMethod handlerMethod = (HandlerMethod) handler; //获取注解 PreAuth preAuth = handlerMethod.getMethodAnnotation(PreAuth.class); //如果注解为空,说明该方法操作不需要进行权限认证,放行即可 if (StringUtils.isEmpty(preAuth)) return true; //获取注解值, String value = preAuth.value(); System.out.println("@PreAuth的值为:" + value); /* 进行逻辑处理, 如权限认证 */ //获取用户的角色权限,判断是否拥有权限,拥有就放行 // 这里我就不多写了,因为每个项目的需求都是不一样的,可以根据自己的需求进行编写 return true; } }
5.测试结果
访问
控制台输出