springboot之aop切面获取请求

springboot之aop切面获取请求

项目场景:

在学习springboot的博客开发中,通过aop切面,对博客中的操作进行记录


问题描述:

问题:
在切面方法中,无法获取请求的参数和类名,方法,ip等

解决方法:

@Before("log()")//调用log方法
    public void doBefore(JoinPoint joinPoint){
        System.out.println("------程序执行之前-----------");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip  = request.getRemoteAddr();
        Object[] args = joinPoint.getArgs();
//        类名-->方法名
        String methodName = joinPoint.getSignature().getDeclaringTypeName()+"-->"
                +joinPoint.getSignature().getName();
        getRequestLog getRequestLog = new getRequestLog(url,ip,methodName,args);
        System.out.println(getRequestLog);
    }

过程:

RequestContextHolder是一个包含了request请求的容器,所以要获取请求中的信息,自然要从容器中获取。
然而RequestContextHolder只能获取RequestAttributes对象,要取得request,必须从ServletRequestAttributes获取
通过查看底层的源码,可以发现ServletRequestAttributes是继承了AbstractRequestAttributes,然后AbstractRequestAttributes继承了RequestAttributes
也就是说ServletRequestAttributesRequestAttributes的子类,所以直接强转就可以了
通过强转后的ServletRequestAttributes直接getRequest,即可得到request对象。

使用了内部类封装所需要打印的值

//    内部类,封装需要得到的值
    private class getRequestLog{
        private String url;
        private String ip;
        private String methodName;
        private Object[] requestParms;

    public getRequestLog() {
    }

    public getRequestLog(String url, String ip, String methodName, Object[] requestParms) {
        this.url = url;
        this.ip = ip;
        this.methodName = methodName;
        this.requestParms = requestParms;
    }

    @Override
    public String toString() {
        return "getRequestLog{" +
                "url='" + url + '\'' +
                ", ip='" + ip + '\'' +
                ", methodName='" + methodName + '\'' +
                ", requestParms=" + Arrays.toString(requestParms) +
                '}';
    }
posted @ 2021-02-04 18:42  小秋呀  阅读(1064)  评论(0编辑  收藏  举报