AOP拦截常用请求内容

1.拦截请求参数

    @Component
    @Aspect
    public class Ascpect {

        private static final Logger log = LogManager.getLogger(Ascpect .class);
        
        @Pointcut("execution(* com.google.lvyou.controller.*.*(..))")
        public void aopMethod(){}
        
        @Around("aopMethod()")
        public Object bindCacheableAdvice(ProceedingJoinPoint pjp) throws Throwable {
        
            Object[] args = joinPoint.getArgs();

            List<String> argList = Arrays.stream(args)
                    .map(arg -> {
                        return arg + "/更换参数";
                    })
                    .collect(Collectors.toList());

            args = argList.toArray();
            return joinPoint.proceed(args) ;
        }
    }

2.拦截注解

eg:@requestMapping

    @Component
    @Aspect
    public class Ascpect {

        private static final Logger logger = LogManager.getLogger(Ascpect .class);
        
       // @Pointcut("execution(* com.google.lvyou.controller.*.*(..))")
       // public void aopMethod(){}
        
        @Around("@annotation(requestMapping)")
        public Object bindCacheableAdvice(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

            Method method = ((MethodSignature)pjp.getSignature()).getMethod();
            log.debug("CacheAroundAdvice invoke start, method=" + method);

            Object[] args = pjp.getArgs();
            log.debug("CacheAroundAdvice invoke, args=" + Arrays.toString(args));


            /**
             * 调用proceed没有参数,隐含地将原始参数传递给底层方法。
             * 从用户的角度来看proceed(),pjp.proceed(pjp.getArgs())做同样的事情。
             * pjp.proceed(new Object[] {...})只有当你想覆盖参数时,你才需要调用。
             */
            return pjp.proceed(); 
            //return pjp.proceed(pjp.getArgs());
        }
    }

3.拦截request

    @Component
    @Aspect
    public class Ascpect {

        private static final Logger logger = LogManager.getLogger(Ascpect .class);

        /**
         * 捕获所有controller层的方法
         */
        @Pointcut("execution(* com.google.lvyou.controller.*.*(..))")
        public void allControllerMethod(){}
        
        @Around("allControllerMethod()")
        public Object bindCacheableAdvice(ProceedingJoinPoint pjp) throws Throwable {

            HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
        
            String requestUrl = request.getScheme() //当前链接使用的协议
                            +"://" + request.getServerName()//服务器地址
                            + ":" + request.getServerPort() //端口号
                            + request.getContextPath() //应用名称,如果应用名称为
                            + request.getServletPath() //请求的相对url -->可作log记录:path(即:requestMapping路径)
                            + "?" + request.getQueryString(); //请求参数


           
            return pjp.proceed(); 
        }
    }

4.拦截所有异常

即:从进入Controller ——> Service ——> Dao 整个过程中的异常!
      有需要抛异常的尽管往上层抛即可,会一并在Controller层最后被AOP捕捉到!
    @Component
    @Aspect
    public class LvyouExceptionHandler {

        private static final Logger logger = LogManager.getLogger(LvyouExceptionHandler .class);

        /**
         * 捕获所有controller层的方法
         */
        @Pointcut("execution(* com.google.lvyou.controller.*.*(..))")
        public void controller(){}
        
        @Around("controller()")
        public Object doBefore(ProceedingJoinPoint pjp) {

            try {
       
                return pjp.proceed(); 
                
            } catch (Throwable throwable) {
                logger.error("LvyouExceptionHandler : " , throwable);
                if (throwable instanceof LvyouException) {
                    return ResultBean.ofError(throwable.getMessage());
                } else if (throwable instanceof IllegalArgumentException) {
                    return ResultBean.ofError(throwable.getMessage());
                } else if (throwable instanceof NullPointerException) {
                    return ResultBean.ofError(throwable.getMessage());
                } else if (throwable instanceof UnirestException) {
                    return ResultBean.ofError("连接超时,请稍后重试!");
                } else if (throwable instanceof BadSqlGrammarException) {
                    return ResultBean.ofError("糟糕,出错啦!");
                } else if (throwable instanceof RuntimeException) {
                    return ResultBean.ofError("糟糕,出错啦!");
                } else {
                    String errorMsg = throwable.toString() == null ? throwable.getMessage() : throwable.toString() ;
                    return ResultBean.ofError(errorMsg == null || errorMsg.equals("") ? "未知错误" : throwable.toString());
                }
            }
        }
    }
    

基本就这些了,更多的等想到再补吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值