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