代码如下
package com.xiaowen.aspect;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* AOP
* @author xiaowen
*
*/
@Aspect
@Component
public class RequestAspect {
private Logger log=Logger.getLogger(RequestAspect.class);
@Pointcut("execution(public * com.xiaowen.controller.*.*(..))")
public void log(){
}
@Before("log()")
public void deBefore(JoinPoint joinPoint){
log.info("方法执行之前");
ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=sra.getRequest();
log.info("url:"+request.getRequestURI());
log.info("ip:"+request.getRemoteHost());
log.info("method:"+request.getMethod());
log.info("class_method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
log.info("args:"+joinPoint.getArgs());
}
@After("log()")
public void doAfter(JoinPoint joinPoint){
log.info("方法执行后...");
}
@AfterReturning(returning="result",pointcut="log()")
public void doAfterReturning(Object result){
log.info("执行返回值:"+result);
}
}