读书人

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

发布时间: 2013-03-16 11:51:46 作者: rapoo

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

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

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

读书人网 >编程

热点推荐