需求:用户使用我们的系统进行操作,如果管理员想要查看:谁在什么时候进行了哪些操作,这个功能应该怎么实现?
使用Spring AOP实现日志输出。首先需要对日志进行自动保存,管理员才能查看,并且日志在前台页面是不能进行增删改的。
1.添加功能描述
日志保存的信息是Controller层的所有操作,所以我们需要在Controller中使用@RequestMapping
注解的name属性对实现的功能进行描述,例如:
@RequestMapping(name="删除用户信息",value = "delete")
public String delete(String id){
userService.delete(id);
return "redirect:/user/list.do";
}
2.保存日志
2.1 编写一个切面类
- 在类上添加注解
@Component
和@Aspect
- 编写一个方法,添加环绕通知注解
@Around
(环绕通知可以获取到目标方法)
1) 让目标方法执行
2) 组装日志对象
3) 调用SysLogService完成保存
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect //声明当前类是切面类
@Component
public class LogAspect {
@Autowired
HttpSession session;
@Autowired
SysLogService sysLogService;
@Around("execution(* com.ljw.web.controller..*.*(..))") //切入点表达式
public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
//1.让目标方法执行
Object result = pjp.proceed();
//保证有用户登陆且有@RequestMapping注解的方法
User loginUser = (User) session.getAttribute("loginUser");
if (loginUser != null) {
//判断目标方法上有无指定注解,有的话才保存日志
//a.获取目标方法
//方法签名对象
MethodSignature signature = (MethodSignature) pjp.getSignature();
//获取方法对象
Method method = signature.getMethod();
//b.判断方法上有无@RequestMapping注解,有的话才操作
if (method.isAnnotationPresent(RequestMapping.class)) {
//获取方法上的注解对象,获取name属性
RequestMapping anno = method.getAnnotation(RequestMapping.class);
//2.组装日志对象
SysLog log = new SysLog();
log.setUserName(loginUser.getUserName());
log.setTime(new Date());
log.setMethod(method.getName());
log.setAction(anno.name());
//3.保存日志
sysLogService.save(log);
}
}
return result;
}
}
2.2 在springmvc.xml中开启AOP自动代理
<!--开启AOP自动代理-->
<aop:aspectj-autoproxy/>
2.3 在SysLogService中编写save方法
@Override
public void save(SysLog sysLog) {
//设置id
sysLog.setId(UUIDUtils.getId());
sysLogDao.save(sysLog);
}