package cn.autoform.fw; import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import cn.autoform.fw.exception.RestResult; @Aspect @Component public class ControllerAspect { /** * 定义拦截规则:拦截cn.autoform.web.controller包下面的所有类中,有@RequestMapping注解的方法。 */ @Pointcut("execution(* cn.autoform.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public void controllerMethodPointcut() { throw new UnsupportedOperationException(); } /** * 拦截器具体实现 * * @param pjp * @return JsonResult(被拦截方法的执行结果,或需要登录的错误提示。) * @throws Throwable */ @Around("controllerMethodPointcut()") public Object interceptor(ProceedingJoinPoint pjp) throws Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); // 获取被拦截的方法 String methodName = method.getName(); // 获取被拦截的方法名 Logger logger = LoggerFactory.getLogger(pjp.getTarget().getClass()); Set allParams = new LinkedHashSet<>(); // 保存所有请求参数,用于输出到日志中 logger.info("请求开始,方法:{}", methodName); Object[] args = pjp.getArgs(); logger.info("请求参数:"); int count = 0; for (Object arg : args) { count++; logger.info("arg{}: {}", count, arg); if (arg instanceof Map) { // 提取方法中的MAP参数,用于记录进日志中 @SuppressWarnings("unchecked") Map map = (Map) arg; allParams.add(map); } else if (arg instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) arg; // 获取query string 或 posted form data参数 Map paramMap = request.getParameterMap(); if (paramMap != null && paramMap.size() > 0) { allParams.add(paramMap); } } } // 一切正常的情况下,继续执行被拦截的方法 Object result = pjp.proceed(); if (result instanceof RestResult) { logger.info("请求结束,方法:{}", methodName); } return result; } }