• 在pom.xml中添加相关的依赖(参考pom.xml文件)
    • 在applicationContext.xml中进行相关的配置(参考applicationContext.xml)
    1. @Component
    2. @Aspect
    3. public class LogAop {
    4. @Autowired
    5. private HttpServletRequest request;
    6. @Autowired
    7. private ISysLogService sysLogService;
    8. //访问时间
    9. private Date startTime;
    10. //访问的类
    11. private Class executionCla;
    12. //访问的方法
    13. private Method executionMethod;
    14. @Before("execution(* com.deya.controller.*.*(..))")
    15. public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException {
    16. startTime = new Date();
    17. executionCla = joinPoint.getTarget().getClass();
    18. String methodName = joinPoint.getSignature().getName();
    19. Object[] args = joinPoint.getArgs();
    20. if (args==null||args.length==0){
    21. //只能获取无参数方法
    22. executionMethod = executionCla.getMethod(methodName);
    23. }else{
    24. Class[] classArgs = new Class[args.length];
    25. for(int i=0;i<args.length;i++){
    26. classArgs[i] = args[i].getClass();
    27. }
    28. executionMethod = executionCla.getMethod(methodName,classArgs);
    29. }
    30. }
    31. @After("execution(* com.deya.controller.*.*(..))")
    32. public void doAfter(JoinPoint joinPoint) throws Exception {
    33. String url;
    34. String ip;
    35. if(executionCla!=null&&executionMethod!=null&&executionCla==LogAop.class){
    36. RequestMapping classAnnotation = (RequestMapping) executionCla.getAnnotation(RequestMapping.class);
    37. if(classAnnotation!=null){
    38. String[] classValue = classAnnotation.value();
    39. //获取方法上的@RequestMapping
    40. RequestMapping methodAnnotation = executionMethod.getAnnotation(RequestMapping.class);
    41. String[] methodValue = methodAnnotation.value();
    42. url=classValue[0]+methodValue[0];
    43. ip = request.getRemoteAddr();
    44. // 获取当前操作的用户
    45. // 从上下文中获得当前登录的用户
    46. SecurityContext context = SecurityContextHolder.getContext();
    47. User user = (User) context.getAuthentication().getPrincipal();
    48. String username = user.getUsername();
    49. SysLog sysLog = new SysLog();
    50. Long executionTime = new Date().getTime()-startTime.getTime();
    51. sysLog.setExecutionTime(executionTime);
    52. sysLog.setIp(ip);
    53. sysLog.setVisitTime(new Date(executionTime));
    54. sysLog.setUrl(url);
    55. sysLog.setUsername(username);
    56. sysLog.setMethod("[类名]"+executionCla.getName()+"[方法名]"+executionMethod.getName());
    57. sysLogService.save(sysLog);
    58. }
    59. }
    60. }
    61. }