问题描述:
每次访问接口的时候都需要验证传递token的有效性,常规的办法就是在每个接口中判断token的有效性,但如果接口个数比较多,那么就会增加开发人员编写代码的工作量。所以考虑是否有一种方法可以省去每次接口中判断token的有效性的代码。其实这个需求与spring管理service层的事物是一样的。
解决方案:
采用AOP的编程思想,通过@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常。
主要代码:
//描述切面类
@Aspect
@Component
public class TokenAop {
/**
* 定义一个切入点
*/
@Pointcut(value="@annotation(cn.lx.common.annotion.TokenAuth)")
private void cutToken(){
}
/**
* 环绕通知(此处采用环绕通知的原因 :1抛出异常后程序不会继续向下执行 2可以改变返回类型)
* @param point
* @return
* @throws Throwable
*/
@Around("cutToken()")
public Object doToken(ProceedingJoinPoint point) throws Throwable{
MethodSignature ms = (MethodSignature) point.getSignature();
Method method = ms.getMethod();
TokenAuth tokenAuth = method.getAnnotation(TokenAuth.class);
String tokenParam = tokenAuth.value();
String tokenValue=null;
//获取拦截方法的参数
String[] parameterNames = ms.getParameterNames();
Object[] args = point.getArgs();
for(int i=0 ; i<parameterNames.length; i++){
if(parameterNames[i].equals(tokenParam)){
tokenValue=(String) args[i];
break;
}
}
if(StringUtils.isBlank(tokenValue)){
throw new TokenAuthException("token不能为空");
}else{
return point.proceed();
}
}
}