logaop

@Component
@Aspect
public class LogAop {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ISysLogService sysLogService;

    private Date visitTime;//开始时间
    private Class clazz;//访问类
    private Method method;//访问的方法

    //前置通知 获取开始时间,执行的类是哪一个,执行的是哪一个方法
    @Before("execution(* com.tang.work.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {

        visitTime = new Date();//访问时间
        clazz = jp.getTarget().getClass();//具体访问的类
        String methodName = jp.getSignature().getName();//获取访问的方法的名称
        Object[] args = jp.getArgs();//获取访问的方法的参数

        //获得具体执行方法的Method对象
        if (args == null || args.length == 0) {
            method = clazz.getMethod(methodName);//只能获取无参方法
        } else {
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                classArgs[i] = args[i].getClass();
            }
            method = clazz.getMethod(methodName, classArgs);
        }

    }

    //后置通知
    @After("execution(* com.tang.work.controller.*.*(..))")
    public void doAfter(JoinPoint jp) throws Exception {
        long time = new Date().getTime() - visitTime.getTime();//获取访问时长

        //获得访问路径url 反射获取注解内容
        String url = "";
        if (clazz != null && method != null && clazz != LogAop.class) {

            //1.获取类上的RequestMapping注解值
            RequestMapping ClassAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
            if (ClassAnnotation != null) {
                String[] classValue = ClassAnnotation.value();

                //2.获得方法上的value值
                RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
                if (methodAnnotation != null) {
                    String[] methodValue = methodAnnotation.value();
                    url = classValue[0] + methodValue[0];
                }
            }

        }

        //获取访问的IP地址
        String ip = request.getRemoteAddr();

        //获取当前当前操作的用户
        SecurityContext context = SecurityContextHolder.getContext();//从上下文中获取当前登录用户
        User user = (User) context.getAuthentication().getPrincipal();
        String username = user.getUsername();

        //将相关信息封装进SysLog
        SysLog sysLog = new SysLog(null, visitTime, username, ip, url,
                time, "[类名]"+clazz.getName() + "[方法名]"+method.getName());
        sysLogService.save(sysLog);
    }


}

AOP相关参考:
https://juejin.im/post/5c47e4b26fb9a049b50726d8#heading-4

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值