注解方式---spring的AOP拦截用户操作

来源:互联网 发布:淘宝日本化妆品代购 编辑:程序博客网 时间:2024/05/02 00:37

1、主要实现用户在进行某项操作时,多数据库的更新、插入和删除详细信息。记录操作时的请求信息。
2、在进入Controller时,生成一个事物ID,在这个Controller中进行的所有DAO操作都绑定该事物ID。并进行记录日志信息。

 

Java代码 
  1. package com.centralsoft.filter;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5. import java.util.Date;  
  6. import java.util.HashMap;  
  7. import java.util.regex.Pattern;  
  8.   
  9. import net.sf.json.JSONObject;  
  10.   
  11. import org.aspectj.lang.ProceedingJoinPoint;  
  12. import org.aspectj.lang.annotation.Around;  
  13. import org.aspectj.lang.annotation.Aspect;  
  14. import org.springframework.beans.factory.annotation.Autowired;  
  15. import org.springframework.beans.factory.annotation.Qualifier;  
  16. import org.springframework.stereotype.Component;  
  17.   
  18. import com.centralsoft.cache.CacheService;  
  19. import com.centralsoft.cache.annotations.Cache;  
  20. import com.centralsoft.cache.entity.MemCacheKey;  
  21. import com.centralsoft.entity.SysLogDetail;  
  22. import com.centralsoft.manager.pub.ThreadBean;  
  23. import com.centralsoft.manager.pub.ThreadId;  
  24. import com.centralsoft.pub.dao.SysLogDAO;  
  25. import com.centralsoft.webservice.pub.DateSHA;  
  26.   
  27. /** 
  28.  * DAO层AOP拦截器,实现记录用户操作过的所有方法和参数,并实现DAO层缓存 
  29.  *  
  30.  * @author Administrator 
  31.  *  
  32.  */  
  33. @Aspect  
  34. @Component  
  35. public class AspectAutoDAOBean {  
  36.   
  37.  @Autowired  
  38.  @Qualifier("CacheService")  
  39.  private CacheService memcache;  
  40.   
  41.  @Autowired  
  42.  @Qualifier("SysLogDAO")  
  43.  private SysLogDAO SysLogDAO;  
  44.   
  45.  @Around("execution(* com.centralsoft.*.dao.Zr*DAO.*(..))")  
  46.  public Object before(ProceedingJoinPoint joinPoint) throws Throwable {  
  47.   // 获取请求事务ID信息  
  48.   ThreadId threadId = new ThreadBean().getThreadId();  
  49.   // 调用方法名称  
  50.   String methodName = joinPoint.getSignature().getName();  
  51.   // 调用参数  
  52.   Object[] args = joinPoint.getArgs();  
  53.   Object object = null;  
  54.   
  55.   // 数据库更新操作日志  
  56.   if (Pattern.matches("(save|insert|add|delete|remove|del|update)[\\S]*",  
  57.     methodName)) {  
  58.    if (threadId != null && threadId.getTransactionalId() != null) {  
  59.     // 获取执行请求事务ID  
  60.     String transactionalId = threadId.getTransactionalId();  
  61.     // 获取执行请求用户ID  
  62.     String userId = threadId.getUserId();  
  63.     SysLogDetail sysLogDetail = new SysLogDetail();  
  64.     sysLogDetail.setXh(transactionalId);  
  65.     sysLogDetail.setUserId(userId);  
  66.     sysLogDetail.setMethod(methodName);  
  67.     JSONObject msg = new JSONObject();  
  68.     // 处理参数  
  69.     for (Object temp : args) {  
  70.      // 获取参数类型,不同参数类型数据处理不一样  
  71.      Class<? extends Object> paramClazz = temp.getClass();  
  72.      String classType = paramClazz.getName();  
  73.      if (classType.equals("java.lang.String")) {  
  74.       msg.put("key", temp);  
  75.      } else if (classType.equals("java.util.HashMap")) {  
  76.       msg.putAll((HashMap<?, ?>) temp);  
  77.      } else if (classType.startsWith("com.")) {  
  78.       try {  
  79.        Field[] f = paramClazz.getDeclaredFields();  
  80.        for (Field field : f) {  
  81.         String fieldName = field.getName();  
  82.         field.setAccessible(true);  
  83.         msg.put(fieldName, field.get(temp));  
  84.        }  
  85.       } catch (SecurityException e) {  
  86.        e.printStackTrace();  
  87.       } catch (IllegalArgumentException e) {  
  88.        e.printStackTrace();  
  89.       }  
  90.      }  
  91.     }  
  92.     sysLogDetail.setMsg(msg.toString());  
  93.     // 记录DAO数据库操作日志  
  94.     SysLogDAO.insertSysLogDetail(sysLogDetail);  
  95.    }  
  96.    // 执行数据库操作  
  97.    object = joinPoint.proceed();  
  98.   
  99.    // 数据库查询缓存  
  100.   } else if (Pattern.matches("(query|load|get|select|read)[\\S]*",  
  101.     methodName)) {  
  102.    // DAO层缓存注解  
  103.    MemCacheKey cacheKey = new MemCacheKey();  
  104.    // 获取cache注解属性  
  105.    Cache cache = null;  
  106.    // 获取请求方法  
  107.    Class<?> cls = joinPoint.getTarget().getClass();  
  108.    // 获取class中的所有方法  
  109.    Method[] methods = cls.getMethods();  
  110.    for (Method m : methods) {  
  111.     // 获取执行方法前的注解信息。  
  112.     if (m.getName().equals(methodName)) {  
  113.      cache = m.getAnnotation(Cache.class);  
  114.      break;  
  115.     }  
  116.    }  
  117.   
  118.    if (cache != null) {  
  119.     // 获取memcacheKey,并进行MD5加密  
  120.     cacheKey = memcacheKey(cache, args);  
  121.     // 判断缓存服务器是否存在该可以值  
  122.     if (memcache.exist(cacheKey.getMemcacheKey())) {  
  123.      object = memcache.get(cacheKey.getMemcacheKey());  
  124.     } else {  
  125.      // 执行数据库操作  
  126.      object = joinPoint.proceed();  
  127.      // 将数据存放进缓存  
  128.      if (cacheKey.getMemcacheKey() != null) {  
  129.       memcache.put(cacheKey.getMemcacheKey(),  
  130.         object == null ? "" : object, new Date(cacheKey  
  131.           .getTime()));  
  132.      }  
  133.     }  
  134.    } else {  
  135.     // 执行数据库操作  
  136.     object = joinPoint.proceed();  
  137.    }  
  138.   } else {  
  139.    // 执行数据库操作  
  140.    object = joinPoint.proceed();  
  141.   }  
  142.   
  143.   return object;  
  144.   
  145.  }  
  146.   
  147.  /** 
  148.   * 获取根据注解中的key获取memcache的含参数key值 
  149.   *  
  150.   * @param cache 
  151.   * @param parameterObject 
  152.   * @return 
  153.   * @author fei.zhao 2011-10-10 
  154.   */  
  155.  @SuppressWarnings("unchecked")  
  156.  private static MemCacheKey memcacheKey(Cache cache, Object[] args) {  
  157.   MemCacheKey tempKey = new MemCacheKey();  
  158.   String key = "";  
  159.   boolean flag = true;  
  160.   StringBuilder keyBuilder = new StringBuilder(32);  
  161.   // 获取注解中的key值  
  162.   String cacheKey = cache.key();  
  163.   Object[] cacheArgs = cacheKey.split("\\.");  
  164.   
  165.   // 设置请求参数在args[]中的序号  
  166.   // key参数进行循环遍历  
  167.   for (Object s : cacheArgs) {  
  168.    // 判断是否是格式$,$...  
  169.    if (s.toString().startsWith("$")) {  
  170.     // 获取参数名称  
  171.     String type = s.toString().substring(1);  
  172.     // 获取参数值  
  173.     Object temp = args[0];  
  174.     // 获取参数类型,不同参数类型数据处理不一样  
  175.     Class<? extends Object> paramClazz = temp.getClass();  
  176.     String classType = paramClazz.getName();  
  177.     if (classType.equals("java.lang.String")) {  
  178.      keyBuilder.append(temp);  
  179.     } else if (classType.equals("java.util.HashMap")) {  
  180.      keyBuilder.append(((HashMap) temp).get(type));  
  181.     } else if (classType.startsWith("com.")) {  
  182.      try {  
  183.       Field f = paramClazz.getDeclaredField(type);// 实体中字段  
  184.       f.setAccessible(true);// 允许访问私有字段  
  185.       keyBuilder.append(f.get(temp));  
  186.      } catch (SecurityException e) {  
  187.       flag = false;  
  188.       e.printStackTrace();  
  189.      } catch (NoSuchFieldException e) {  
  190.       flag = false;  
  191.       e.printStackTrace();  
  192.      } catch (IllegalArgumentException e) {  
  193.       flag = false;  
  194.       e.printStackTrace();  
  195.      } catch (IllegalAccessException e) {  
  196.       flag = false;  
  197.       e.printStackTrace();  
  198.      }  
  199.     }  
  200.    } else {  
  201.     keyBuilder.append(s);  
  202.    }  
  203.    // 每个参数后面添加 “.”号分隔  
  204.    keyBuilder.append(".");  
  205.   }  
  206.   if (args.length == 3) {  
  207.    keyBuilder.append(args[1] + ".").append(args[2]);  
  208.   }  
  209.   if (flag == true) {  
  210.    key = keyBuilder.toString();  
  211.    tempKey.setMemcacheKey(DateSHA.shaEncrypt(key));  
  212.    tempKey.setTime(cache.time());  
  213.   }  
  214.   return tempKey;  
  215.  }  
  216. }  
原创粉丝点击