annotation+reflection+interceptor实现自定义权限校验
封装需准备如下:
- 方法的注解:利用interceptor通过该方法注解进行权限校验
- webMvcConfig配置类:添加interceptor拦截器
- 权限校验拦截器类:对有注解的方法进行拦截,进行权限校验
- controller类:进行测试
代码示例:
/**
* 自定义权限注解
*/
@Target({ElementType.METHOD,ElementType.TYPE})//作用范围为类或方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface Auth {
//是否需要验证,true为校验,false为不校验
//自定义注解+反射+拦截器 实现权限校验
boolean key() default true;
}
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Auth auth = findAuthCheck(handlerMethod);
// 若没有添加权限注解则直接跳过,允许访问
if (auth == null) {
return true;
}
// 获取权限注解中的值
boolean key = auth.key();
// 演示,若key为true则校验通过,否则不通过
if (!key) {
System.out.println("校验未通过");
throw new RuntimeException("校验未通过");
}
return true;
}
private Auth findAuthCheck(HandlerMethod handlerMethod) {
// 在方法上的注解
// 通过反射获取
Auth annotation = handlerMethod.getMethodAnnotation(Auth.class);
if (annotation == null) {
// 在类上的注解
// 通过反射获取
annotation = handlerMethod.getBeanType().getAnnotation(Auth.class);
}
return annotation;
}
}
@Component
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor).addPathPatterns("/**");
}
}
@RestController
public class DemoController {
@RequestMapping("/hello")
@Auth
public Object hello() {
return "已通过权限校验,顺利进入该方法";
}
@RequestMapping("/hello2")
@Auth(key = false)
public Object hello2() {
return "已通过权限校验,顺利进入该方法";
}
@RequestMapping("/hello3")
public Object hello3() {
return "已通过权限校验,顺利进入该方法";
}
}
已测试,结果符合预期
小结:注解是对java类的一种标注,通过拦截器对所有请求方法进行拦截,若方法上有注解标注则进行权限校验,需理解封装的设计模式