SpringBoot使用AOP获取请求参数
原文地址:http://www.voidcn.com/article/p-bpynkczg-byy.html
package com.*.aop;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* @Description //请求参数aop
**/
@Component
@Aspect
@Slf4j
public class RequestParameterAop {
/**
* @Description: 定义需要拦截的切面
* @Return: void
* @Author: yangli
* @Date: 2019/9/06-10:17
**/
@Pointcut("execution(* com.*.controller.*Controller.*(..))")
public void methodArgs() {
}
@Around("methodArgs()")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
// 获取请求参数进行打印
Signature signature = joinPoint.getSignature();
JSONObject signatureJson = JSON.parseObject(JSON.toJSONString(signature));
// 方法名
String methodName = signatureJson.getString("name");
// 类名
String serviceName = signatureJson.getString("declaringType");
// 参数名数组
JSONArray parameterNames = signatureJson.getJSONArray("parameterNames");
// 构造参数组集合
List<Object> argList = new ArrayList<>();
for (Object arg : joinPoint.getArgs()) {
// request/response无法使用toJSON
if (arg instanceof HttpServletRequest) {
argList.add("request");
} else if (arg instanceof HttpServletResponse) {
argList.add("response");
} else {
argList.add(JSON.toJSON(arg));
}
}
try {
log.error("{} -> 方法({}) -> 参数:{} - {}", serviceName, methodName, JSON.toJSON(parameterNames), JSON.toJSON(argList));
} catch (Exception e) {
log.error("参数获取失败: {}", e.getMessage());
}
result = joinPoint.proceed();
return result;
}
}

浙公网安备 33010602011771号