package com.whyc.aop;
|
|
import com.whyc.service.OperationLogService;
|
import org.aspectj.lang.JoinPoint;
|
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.aspectj.lang.reflect.MethodSignature;
|
import org.springframework.beans.factory.annotation.Autowired;
|
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.servlet.http.HttpServletRequest;
|
import java.util.HashMap;
|
|
/**
|
* spring aop,面向切面;
|
* 切面为Controller
|
* 切点为本类中@PointCut的表达式
|
* 具体连接点为JoinPoint
|
* 通知方式选用doAfterReturning
|
*/
|
|
@Aspect
|
@Component
|
public class OperationLogAspect {
|
|
@Autowired
|
private OperationLogService operationLogService;
|
|
/**
|
* aop表达式解释:
|
* 第一个*:返回类型,所有类型
|
* 第二个*:类名,所有类名
|
* 第三个*:方法名,所有方法
|
* 第一个..:whyc当前包和子包
|
*/
|
@Pointcut("execution(public * com.whyc..controller.*.add*(..)) " +
|
"|| execution(public * com.whyc..controller.*.delete*(..)) " +
|
"|| execution(public * com.whyc..controller.*.update*(..))")
|
private void operation(){}
|
|
@AfterReturning(pointcut = "operation()",returning = "response")
|
public void doAfterReturningOperation(JoinPoint joinPoint,Object response){
|
|
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
|
HttpServletRequest request = requestAttributes.getRequest();
|
//获取当前Session用户名
|
String userName = (String) requestAttributes.getAttribute("user", RequestAttributes.SCOPE_SESSION);
|
//获取当前用户ip
|
String currentUserTerminalIp = request.getRemoteAddr();
|
//执行的类全名
|
String fullClassName = joinPoint.getSignature().getDeclaringTypeName().toString();
|
//获取类型
|
String[] fullClassNameSplit = fullClassName.split("\\.");
|
String className = fullClassNameSplit[fullClassNameSplit.length-1].replace("Controller","模块");
|
if(fullClassName.contains("app")){
|
className+="-安卓端";
|
}
|
//执行的方法
|
String methodName = joinPoint.getSignature().getName();
|
String methodType = "";
|
if(methodName.contains("update")){
|
methodType = "更新";
|
}else if(methodName.contains("add")){
|
methodType ="新增";
|
}else{
|
methodType="删除";
|
}
|
//获取方法的参数
|
String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
|
Object[] args = joinPoint.getArgs();
|
|
HashMap<String, Object> map = new HashMap<>();
|
for (int i = 0; i < parameterNames.length; i++) {
|
map.put(parameterNames[i],args[i]);
|
}
|
|
//拼接成操作日志内容
|
String content = "执行了"+className+"的"+methodType+"操作," +
|
"具体调用方法为:"+methodName+","+
|
"参数信息为:"+map;
|
operationLogService.record(content,userName,currentUserTerminalIp);
|
|
}
|
|
}
|