一創(chuàng)建一個自定義注解
// String value() default "";
}
二 創(chuàng)建一個切面類
@Component
public class MyAspect {
@Autowired
private LogsService logsService;
//搜索UsersService類中的所有帶@MyLog的方法
@Pointcut("execution(* com.qianfeng.wc.service.UsersService.*(..))&&@annotation(com.qianfeng.wc.aop.MyLog)")
public void gub() {
}
@After("gub()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
Logs logs = new Logs();
// 接收到請求扯旷,記錄請求內(nèi)容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest req = attributes.getRequest();
String[] split = req.getRequestURL().toString().split("/");
logs.setUserip(req.getRemoteAddr());// 獲取請求的ip地址
logs.setRequrl(req.getRequestURL().toString());// 獲取請求的url
String methodame = joinPoint.getSignature().getName();// 獲取類方法
if (methodame.contains("select")) {
logs.setActiondetail(split[3].concat("_查詢"));
} else if (methodame.contains("insert")) {
logs.setActiondetail(split[3].concat("_添加"));
} else if (methodame.contains("update")){
logs.setActiondetail(split[3].concat("_修改"));
} else if (methodame.contains("delete")) {
logs.setActiondetail(split[3].concat("_刪除"));
} else {
logs.setActiondetail("未知操作");
}
logs.setClassname(joinPoint.getSignature().getDeclaringTypeName());// 獲取類名
logs.setMethodame(methodame);
Object[] args = joinPoint.getArgs(); // 獲取請求參數(shù)
if (args[0].toString()!=null){
logs.setOperationdata(args[0].toString());
}else{
logs.setOperationdata("無");
}
logs.setUpdatetime(new Timestamp(System.currentTimeMillis()));
// logs.setRemarks();
req.setAttribute("logs",logs);
try {
logsService.insert(logs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
三 在實現(xiàn)類中需要的方法上加上@MyLog注解
@MyLog
public int deleteById(Integer id) {
return this.usersDao.deleteById(id);
}
params.put("url", req.getRequestURL().toString()); // 獲取請求的url
params.put("method", req.getMethod()); // 獲取請求的方式
params.put("ip", req.getRemoteAddr()); // 獲取請求的ip地址
params.put("className", joinPoint.getSignature().getDeclaringTypeName()); // 獲取類名
params.put("classMethod", joinPoint.getSignature().getName()); // 獲取類方法
params.put("args", joinPoint.getArgs().toString()); // 請求參數(shù)