一、数据表和实体类的准备
我们要管理系统日志,那么数据表和实体类是必不可少的,这里编写一个简单的实体类:
/** * 系统日志实体类 * * @author Mr.song * @date 2019/05/09 17:57 */ public class SysLog implements Serializable { private String id; private String userName; private String ip; private Date time; private String method;//访问的方法名称 private String action;//进行的操作名称 //... }
同时我们还要完成Dao层和Service层相应的添加、查询方法。(比较简单,这里忽略)
这里采用基于注解的环绕通知
/** * 用于记录日志的通知 * * @author Mr.song * @date 2019/05/09 19:50 */ @Aspect //声明为切面类 @Component public class LogAspect { @Autowired private SysLogService sysLogService; @Autowired private HttpSession session; @Autowired private HttpServletRequest request; @Around("execution(* cn.dintalk.web.controller.*.*.*(..))") public Object aroundSysLog(ProceedingJoinPoint pjp) { try { //获取到切入点的签名 Signature signature = pjp.getSignature(); //将签名转为方法的签名 if (signature instanceof MethodSignature) { MethodSignature ms = (MethodSignature) signature; //获取方法 Method method = ms.getMethod(); //获取注解(判断是否为RequestMapping类型的) if (method.isAnnotationPresent(RequestMapping.class)) { //创建日志对象 SysLog sysLog = new SysLog(); //设置日志的操作方法和名称 sysLog.setMethod(method.getName()); //获取方法上的注解,设置日志的操作名称 RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); sysLog.setAction(requestMapping.name()); //设置日志的用户相关信息 User user = (User) session.getAttribute("user"); if (user == null || UtilFuns.isEmpty(user.getUserName())) { //匿名访问 sysLog.setUserName("匿名"); } else { sysLog.setUserName(user.getUserName()); } //设置日志的ip和时间 sysLog.setTime(new Date()); sysLog.setIp(request.getRemoteAddr()); //添加日志 sysLogService.add(sysLog); } } //获取当前切入点方法的所需参数 Object[] args = pjp.getArgs(); //执行方法并返回 Object obj = pjp.proceed(args); return obj; } catch (Throwable e) { throw new RuntimeException(e); } } }
<!-- 开启切面注解支持 --> <aop:aspectj-autoproxy/>
//展示用户列表 @RequestMapping(value = "/list",name = "查看用户列表") public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size){ //1.查询到企业下用户的分页数据 PageInfo pageInfo = userService.findAll(companyId, page, size); //2.保存到域中进行转发 request.setAttribute("page",pageInfo); return "system/user/user-list"; }
关注微信公众号,随时随地学习