aop實現接口請求參數打印


1.面向切面編程(AOP)Aspect Oriented Programming。

切面編程的目的是為了把通用邏輯從業務邏輯分離出來。

作為一個Java開發,基本是離不開spring的,spring 的核心基礎功能就是Ioc和Aop。

這里我的應用是打印接口請求的URL、IP、請求方式以及入參,方便接口調試。

2.代碼如下,拷貝可以直接使用,很方便。沒基礎的同學,請自己先行補充理論知識。

 

@Aspect
@Component
public class ParamLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ParamLogAspect.class);

    /**
     * 定義一個切點
     * 切入 controller包
     *      api包
     *      commonInterface.controller
     *      commonInterface.service.impl
     *      下的所有類的所有方法
     */
    @Pointcut("execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.controller.*.*(..))" +
            "||execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.api.*.*(..)) " +
            "||execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.commonInterface.controller.*.*(..)) ")
    public void validateMethod(){

    }

    @Before("validateMethod()")
    public void validate(JoinPoint joinPoint){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("=====URL : " + request.getRequestURL().toString());
        logger.info("=====IP : " + request.getRemoteAddr()+"  HTTP_METHOD :" + request.getMethod());
        StringBuffer body = new StringBuffer();
        Object[] arguments = joinPoint.getArgs();
        //獲取方法的參數
        if(arguments.length!=0){
            try {
                Map<String, Object> params = params = (Map<String, Object>)arguments[0];
                for (String key:params.keySet()
                ) {
                    body.append(key).append(":").append(params.get(key)).append(";");
                }
                if(body.toString().length()==0){
                    logger.info("body參數為空!");
                }else {
                    logger.info("=====方法接收參數[{}]",body.toString().substring(0,body.toString().length()-1));
                }

            }catch (Exception ex){
                logger.info("=====方法接收參數[{}]",arguments[0].toString());
            }
        }

        //獲取問號拼接的參數:
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            if (!StringUtils.isEmpty(request.getParameter(paraName))) {
                logger.info("=====問號后param : " + paraName + " : " + request.getParameter(paraName));
            }
        }

    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM