通过自定义注解,然后在控制层方法上加上此注解,通过aop切面拦截到该方法,获取注解值,实现操作日志管理。
1 自定义注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LoggerAnnonation {
String op();
}
2 编写切面(在普通类获取request可用使用RequestContextHolder .getCurrentRequestAttributes())
import com.yc.entity.Logger;
import com.yc.entity.User;
import com.yc.service.LoggerService;
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.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author an-ping
* @date 2019/3/30
*/
@Aspect
@Component
public class LoggerAspectj {
@Pointcut("execution(* com.yc.controllers..*(..))")
public void pointcut(){}
@Resource(name="loggerServiceImpl")
LoggerService loggerService;
@After(value = "pointcut()")
public void after(JoinPoint pjp) throws Throwable{
String methodName= pjp.getSignature().getName();
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//String str = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_SESSION);
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
User user=(User)request.getSession().getAttribute("user");
String ip=request.getRemoteAddr(); //获取ip
String op="";
if(ip.equals("0:0:0:0:0:0:0:1")){
ip="127.0.0.1";
}
// System.out.println(ip);
if(user!=null){
MethodSignature ms=null;
ms=(MethodSignature)pjp.getSignature();
Class[] argType=ms.getMethod().getParameterTypes();
Method method=pjp.getTarget().getClass().getMethod(methodName,argType);
if (method.isAnnotationPresent(LoggerAnnonation.class)) {
LoggerAnnonation loggerAnnonation=method.getAnnotation(LoggerAnnonation.class);
op=loggerAnnonation.op();
// System.out.println(op+"操作日志");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(new Date());
Logger logger=new Logger();
logger.setIp(ip);
logger.setOp(op);
logger.setTime(time);
loggerService.add(logger);
}
}
}
}