1. Spring AOP + 注解 实现拦截(包括Controller层的拦截) -
- 定义注解
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String remark() default "操作日志记录";
}
注意:在Spring的主配置文件配置组件扫描 ``` ``` -
- 定义AOP拦截器
@Component
@Aspect
public class LogAspect implements Serializable {
private static final long serialVersionUID = 1L;
//定义拦截的方法
@Pointcut("@annotation(com.emvc.aspect.LogAnnotation)")
public void methodCachePointcut() {
}
//拦截处理
@After("methodCachePointcut() && @annotation(logRemark)")
public void doAfter(JoinPoint jp, LogAnnotation logRemark) throws ClassNotFoundException, NotFoundException {
//业务处理
}
}
注:要在spring的配置文件配置, 特别的Controller的代理默认是JDK,如果想要用AOP拦截Controller的方法,需要将Controller的代理交由Cglib(在Spring mvc的配置文件配置 ),expose-proxy将Controller代理交由Cglib。
2.AOP拦截后的参数处理(利用反射获取方法的参数名及其值)
/**
* 返回 参数名=值;
**/
private static String writeLogInfo(String[] paramNames, JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < args.length; k++) {
Object arg = args[k];
sb.append(paramNames[k]);
sb.append("=" + arg + ";");
}
return sb.toString();
}
/**
* 得到方法参数的名称
*
* @param cls this.getClass(),
* @param clazzName jp.getTarget().getClass().getName()
* @param methodName jp.getSignature().getName()
* @return 参数名数组
* @throws NotFoundException
*/
private String[] getFieldsName(Class cls, String clazzName, String methodName) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
return null;
}
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++) {
paramNames[i] = attr.variableName(i + pos); // paramNames即参数名
}
return paramNames;
}