import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Aspect
@Component
public class HttpAspect
{
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
ThreadLocal<Long> startTime = new ThreadLocal<Long>();
/*
* 定义一个切入点
*/
@Pointcut("execution(public * com.dcsoft.controller.*.*(..))")
public void log()
{
}
/*
* 通过连接点切入
*/
@Before("log()")
public void doBefore(JoinPoint joinPoint)
{
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("url={}", request.getRequestURL());
logger.info("method={}", request.getMethod());
logger.info("ip={}", request.getRemoteAddr());
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("args={}", joinPoint.getArgs());
//获取所有参数方法
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String paraName = enu.nextElement();
System.out.println(paraName + ": " + request.getParameter(paraName));
}
}
@After("log()")
public void doAfter()
{
logger.info("结束");
}
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object)
{
if (null == object) {
logger.info("response={}", "空");
} else {
logger.info("response={}", object.toString());
}
logger.info("WebLogAspect.doAfterReturning()");
//logger.info("请求耗时(毫秒) : " + (System.currentTimeMillis() - startTime.get()));
}
}