切面(Aspect)获取ServletRequest请求参数和返回值

 可以获取到ServletRequest里面的参数,这里记录一下,以后可能用得着,哈哈哈

/**
 * @author wcybaonier
 */
@Aspect
@Component
@Slf4j
public class TokenWhiteListAspect {
    @Resource
    private RedisMapper redisMapper;
    /**
     * 定义切点Pointcut
     * 第一个*号:表示返回类型, *号表示所有的类型
     * 第二个*号:表示类名,*号表示所有的类
     * 第三个*号:表示方法名,*号表示所有的方法
     * 后面括弧里面表示方法的参数,两个句点表示任何参数
     */
    @Pointcut("execution(* com.idc.*..*Controller.*(..))")
    public void executionService() {}
 
    /**
     * 方法调用之前调用
     * @param joinPoint
     */
    @Before(value = "executionService()")
    public void doBefore(JoinPoint joinPoint){
        String requestId = String.valueOf(UUID.randomUUID());
        MDC.put("requestId",requestId);
        log.info("类名:"+joinPoint.getSignature().getDeclaringTypeName()+
                "、方法名: "+joinPoint.getSignature().getName()+"()、====>@Before:请求参数为:{}",Arrays.toString(joinPoint.getArgs()));
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        BodyReaderHttpServletRequestWrapper request = (BodyReaderHttpServletRequestWrapper) attributes.getRequest();
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        
        String token = request.getRequest().getParameterMap().get("token")[0];
        log.info("token------------"+token);
        String obj = redisMapper.getObject("idc_token::" + token);
        if (obj == null) {
            // 登陆过期
            log.error("token 验证失败,请重新登陆!!!");
            log.info("token 验证失败,请重新登陆!!!");
            throw new CommonRuntimeException("token 验证失败,请重新登陆!!!");
        }
    }
 
    /**
     * 方法之后调用
     * @param joinPoint
     * @param returnValue 方法返回值
     */
    @AfterReturning(pointcut = "executionService()",returning="returnValue")
    public void  doAfterReturning(JoinPoint joinPoint,Object returnValue){
        log.info("类名:"+joinPoint.getSignature().getDeclaringTypeName()+
                "、方法名: "+joinPoint.getSignature().getName()+"()、====>@Before:请求参数为:{}",Arrays.toString(joinPoint.getArgs()));
        // 处理完请求,返回内容
        MDC.clear();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39706515/article/details/130327291
今日推荐