项目背景:
需要对项目的前后端进行加密传输,后台统一处理,此时我们经常会用到spring的AOP,方便快捷,以下为书写过程中的记录以及总结。
项目环境:springboot
【说明】前台加解密,以及后台加解密过程忽略,各位大佬根据自己项目书写即可。
主要业务代码如下:
@Pointcut("@annotation(com.zoro.drei.common.annotation.SecurityAsIn)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
//SecurityAsIn为空即默认标准设置
SecurityAsIn SecurityAsIn = null;
boolean flag = false;
try {
MethodSignature msig = (MethodSignature) point.getSignature();
Method pointMethod = point.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());
SecurityAsIn = pointMethod.getAnnotation(SecurityAsIn.class);//切点方法上获取注解
if (SecurityAsIn != null && SecurityAsIn.requestAes()) {
//加解密业务处理
。。。。省略
}
} catch (Exception e) {
logger.error("请求解析异常:", e);
return Result.error("请求解析异常");
}
Object result = null;
try {
// 方法形参
Object[] methodArgs = point.getArgs();
// 执行方法
result = point.proceed(methodArgs);
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
主要使用一个切入点,一个环绕方法,其他的几个暂时没用到。
其中最主要的语句为以下两句,缺一不可;
// 方法形参
Object[] methodArgs = point.getArgs();
以上这一句是获取经过加密或者解密后的参数
// 执行方法
result = point.proceed(methodArgs);
此句最为重要,意为执行方法,传入参数和不传入参数区别很大,传入参数代表把解密或者加密后的数据返回继续执行。不传入参数意为直接执行,与我们的初中并不相符。所以必须把处理过的参数返回controller,controller接收真正意义上的数据,并进行处理。
controller层部分代码
//aop接口
@Aspect()
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST)
public Result test(@RequestParam String a1,@RequestParam String a2,@RequestParam String a3,@RequestBody Map map) {
//...
}
不加aop接口上面的几个参数都为密文,加上aop后就是我们需要的效果。以及注意上文红色部分。
PS:真正的留下了没有技术的眼泪,懂就是几秒钟的问题,不懂就是几个小时的问题。