SpringBoot实战项目(十七)--使用拦截器实现系统日志功能

系统日志一般用来记录用户登录系统后的一些操作记录

谁(当前登录用户)--- 什么时间---- 做了哪些操作

 

新建sys_log(日志记录表)

1 CREATE TABLE `sys_log` (
2   `logId` int(11) NOT NULL AUTO_INCREMENT,
3   `userName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
4   `msg` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
5   `createTime` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP,
6   PRIMARY KEY (`logId`) USING BTREE
7 ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

实体类

1 @Data
2 @ToString
3 public class SysLog implements Serializable {
4 
5     private Long logId;
6     private String userName;
7     private String msg;
8     private String createTime;

利用自定义拦截器---MyInterceptor实现业务逻辑及数据保存操作

 1 package com.beilin.interceptor;
 2 
 3 
 4 
 5 import com.beilin.dao.LogDao;
 6 import com.beilin.entity.SysLog;
 7 import com.beilin.entity.SysUser;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.context.annotation.Bean;
10 import org.springframework.web.servlet.HandlerInterceptor;
11 import org.springframework.web.servlet.ModelAndView;
12 
13 
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import java.util.Date;
17 
18 /**
19  *  拦截器
20  */
21 public class MyInterceptor implements HandlerInterceptor {
22 
23     @Autowired
24     private LogDao logDao;
25 
26  
27 
28     @Override
29     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
30         //获取当前用户
31         SysUser user = (SysUser)request.getSession().getAttribute("user");
32         Object msg = request.getSession().getAttribute("msg");
33         //传操作的JAVABEAN过来
34         if (user != null && msg != null) {
35             //写入日志
36             SysLog log = new SysLog();
37             log.setUserName(user.getUserName());
38             log.setMsg(msg.toString());
39             logDao.save(log);
40             //删除msg
41             request.getSession().removeAttribute("msg");
42         }
43     }
44 
45 }

(注意:拦截器原本需要重写三个方法的,这里为了方便直观,只保留所需的,完整的最后附上)

这里都有相关文字说明,不再一一赘述,只要了解了设计思想其实很容易

用户做新增,修改,删除操作的时候才需要做记录,查看之类的就没必要

 1  @PostMapping("/add")
 2     @ResponseBody
 3     //新增用户
 4     public Results<SysUser> save(SysUser sysUser, Integer roleId, HttpServletRequest request) {
 5        List<SysUser> results = userService.getUser(sysUser.getUserName(),sysUser.getTelephone(),sysUser.getEmail());
 6        if (results != null && results.size()>0){
 7            for (SysUser user : results){
 8                //判断用户名是否已存在
 9                 if (user.getUserName().equals(sysUser.getUserName())){
10                         return Results.failure(ResponseCode.USERNAME_REPEAT.getCode(), ResponseCode.USERNAME_REPEAT.getMessage());
11                     }
12                      //判断手机号是否已存在
13                     if (user.getTelephone().equals(sysUser.getTelephone())) {
14                         return Results.failure(ResponseCode.PHONE_REPEAT.getCode(), ResponseCode.PHONE_REPEAT.getMessage());
15                     }
16                     //判断邮箱是否已存在
17                     if (user.getEmail().equals(sysUser.getEmail())) {
18                         return Results.failure(ResponseCode.EMAIL_REPEAT.getCode(), ResponseCode.EMAIL_REPEAT.getMessage());
19                     }
20            }
21        }
22        sysUser.setStatus(1);
23        //MD5加密
24        sysUser.setPassWord(Md5Cipher.encryptWithSalt(sysUser.getPassWord()));
25        request.getSession().setAttribute("msg","新增了用户资料:"+sysUser.toString());
26             return userService.save(sysUser,roleId);
27     }

如代码所示,msg记录用户的操作内容,这里sysUser.toString()方法我只取几个有意义的值,有兴趣的可以自己重写或者拼接

SpringBoot实战项目(十七)--使用拦截器实现系统日志功能

 

 

 这样,sys_log表的字段都有值了,接下来把信息保存到数据库即可

SpringBoot实战项目(十七)--使用拦截器实现系统日志功能

 

 

 SpringBoot实战项目(十七)--使用拦截器实现系统日志功能

 这里比较简单不需要写service层了

项目最终效果----

 SpringBoot实战项目(十七)--使用拦截器实现系统日志功能

 

 

SpringBoot实战项目(十七)--使用拦截器实现系统日志功能
 1 package com.beilin.interceptor;
 2 
 3 
 4 
 5 import com.beilin.dao.LogDao;
 6 import com.beilin.entity.SysLog;
 7 import com.beilin.entity.SysUser;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.context.annotation.Bean;
10 import org.springframework.web.servlet.HandlerInterceptor;
11 import org.springframework.web.servlet.ModelAndView;
12 
13 
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import java.util.Date;
17 
18 /**
19  *  拦截器
20  */
21 public class MyInterceptor implements HandlerInterceptor {
22 
23     @Autowired
24     private LogDao logDao;
25 
26     @Override
27     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
28         //获取登录时保存到session的用户信息
29         SysUser user = (SysUser) request.getSession().getAttribute("user");
30         if (user == null) {
31             //拦截未登录请求
32             request.getRequestDispatcher("/login").forward(request, response);
33             return false;
34         }
35         return true;
36     }
37 
38     @Override
39     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
40 
41     }
42 
43     @Override
44     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
45         //获取当前用户
46         SysUser user = (SysUser)request.getSession().getAttribute("user");
47         Object msg = request.getSession().getAttribute("msg");
48         //传操作的JAVABEAN过来
49         if (user != null && msg != null) {
50             //写入日志
51             SysLog log = new SysLog();
52             log.setUserName(user.getUserName());
53             log.setMsg(msg.toString());
54             logDao.save(log);
55             //删除msg
56             request.getSession().removeAttribute("msg");
57         }
58     }
59 
60 }
MyInterceptor

 

上一篇:mybatis更新数据(传对象 传 Map参数)


下一篇:TkMybatis常用方法