Springboot中AOP获取请求接口的参数

2022-06-24 12:55:16

创建自定义注解

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {

}

测试实体

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TEST {
    private String[] a;
    private ArrayList b;
}

测试接口,为接口上加入自定义注解@Log

    @PostMapping("/testC3")
    @Log
    public String testC3(@RequestParam("name") String name,@RequestBody TEST test){
        return JSON.toJSONString(test)+name;
    }

切面(包含了获取参数的方法)

@Aspect
@Component
public class LogAspect {


    /**
     *  层切点
     */
    @Pointcut("@annotation(log)")
    public void controllerAspect(Log log) {
    }

    @After("controllerAspect(log)")
    public void After(JoinPoint pjp, Log log)  {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
         HttpServletRequest request = sra.getRequest();
        String name = request.getParameter("name");//获取指定key参数
        Map<String, String[]> parameterMap = request.getParameterMap();//获取全部Parameter参数
        Object[] args = pjp.getArgs();//获取所有参数包括body和Parameter

        String[] names = parameterMap.get("name");
        System.out.println(name);
        System.out.println(names[0]);
        System.out.println(JSON.toJSONString(args));
    }
}

测试运行

 控制台成功打印

  • 作者:小王同鞋
  • 原文链接:https://blog.csdn.net/m0_60215634/article/details/124795430
    更新时间:2022-06-24 12:55:16