SpringBoot使用AOP获取请求参数


  最近试了下拦截controller方法查看请求参数,方式如下:

  1 import com.alibaba.fastjson.JSON;
  2 import com.google.common.base.Stopwatch;
  3 import io.swagger.annotations.Api;
  4 import io.swagger.annotations.ApiOperation;
  5 import lombok.extern.slf4j.Slf4j;
  6 import org.aspectj.lang.ProceedingJoinPoint;
  7 import org.aspectj.lang.Signature;
  8 import org.aspectj.lang.annotation.Around;
  9 import org.aspectj.lang.annotation.Aspect;
 10 import org.aspectj.lang.annotation.Pointcut;
 11 import org.aspectj.lang.reflect.MethodSignature;
 12 import org.springframework.stereotype.Component;
 13 import org.springframework.web.context.request.RequestContextHolder;
 14 import org.springframework.web.context.request.ServletRequestAttributes;
 15 
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpServletResponse;
 18 import java.util.ArrayList;
 19 import java.util.List;
 20 import java.util.concurrent.TimeUnit;
 21 
 22 /**
 23  * @Description //请求参数aop
 24  **/
 25 @Component
 26 @Aspect
 27 @Slf4j
 28 public class RequestParameterAop {
 29 
 30     /**
 31      * @Description: 定义需要拦截的切面
 32      * @Pointcut("execution(* com.*.controller.*Controller.*(..))")
 33      * @Return: void
 34      **/
 35     @Pointcut("execution(* com.*.controller.*Controller.*(..))")
 36     public void methodArgs() {
 37 
 38     }
 39 
 40     @Around("methodArgs()")
 41     public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
 42         Object result;
 43 
 44         Stopwatch stopwatch = Stopwatch.createStarted();
 45         result = joinPoint.proceed();
 46         try {
 47             HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
 48             // ip地址
 49             String ipAddr = getRemoteHost(request);
 50             // 请求路径
 51             String requestUrl = request.getRequestURL().toString();
 52 
 53             // 获取请求参数进行打印
 54             Signature signature = joinPoint.getSignature();
 55             MethodSignature methodSignature = (MethodSignature) signature;
 56 
 57             // 类名
 58             // swagger中文注释名
 59             String classCommentName = methodSignature.getMethod().getDeclaringClass().getAnnotation(Api.class).tags()[0];
 60             String[] sourceName = signature.getDeclaringTypeName().split("\\.");
 61             String className = sourceName[sourceName.length - 1] + "[" + classCommentName +"]";
 62 
 63             // 方法名
 64             // swagger中文注释名
 65             String methodCommentName = methodSignature.getMethod().getAnnotation(ApiOperation.class).value();
 66             String methodName = signature.getName() + "[" + methodCommentName + "]";
 67 
 68             // 参数名数组
 69             String[] parameterNames = ((MethodSignature) signature).getParameterNames();
 70             // 构造参数组集合
 71             List<Object> argList = new ArrayList<>();
 72             for (Object arg : joinPoint.getArgs()) {
 73                 // request/response无法使用toJSON
 74                 if (arg instanceof HttpServletRequest) {
 75                     argList.add("request");
 76                 } else if (arg instanceof HttpServletResponse) {
 77                     argList.add("response");
 78                 } else {
 79                     argList.add(JSON.toJSON(arg));
 80                 }
 81             }
 82 
 83             stopwatch.stop();
 84             long timeConsuming = stopwatch.elapsed(TimeUnit.MILLISECONDS);
 85 
 86             log.error("请求源IP【{}】 -> 请求URL【{}】\n{} -> {} -> 请求耗时:[{}]毫秒 \n请求参数:{} -> {}\n请求结果:{}",
 87                     ipAddr, requestUrl,
 88                     className, methodName, timeConsuming,
 89                     JSON.toJSON(parameterNames), JSON.toJSON(argList),
 90                     JSON.toJSON(result));
 91         } catch (Exception e) {
 92             log.error("参数获取失败: {}", e.getMessage());
 93         }
 94 
 95         return result;
 96     }
 97 
 98     /**
 99      * 获取目标主机的ip
100      * @param request
101      * @return
102      */
103     private String getRemoteHost(HttpServletRequest request) {
104         String ip = request.getHeader("x-forwarded-for");
105         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
106             ip = request.getHeader("Proxy-Client-IP");
107         }
108         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
109             ip = request.getHeader("WL-Proxy-Client-IP");
110         }
111         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
112             ip = request.getRemoteAddr();
113         }
114         return ip.contains("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
115     }
116 
117 }

打完收工~


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM