一、创建ThreadLocal类
package com.lingyang.system.util.thread;
import com.lingyang.system.data.vo.admin.AdminDetailVO;
/**
* @author **文
* @Description:
* @createDate 2024/8/14 16:01
**/
public class AdminThreadLocal {
private static ThreadLocal<AdminDetailVO> AdminThreadLocal = new ThreadLocal<>();
/**
* 添加当前登录用户方法 在拦截器方法执行前调用设置获取用户
* @param admin
*/
public static void addCurrentUser(AdminDetailVO admin){
AdminThreadLocal.set(admin);
}
/**
* 获取当前登录用户方法
*/
public static AdminDetailVO getCurrentUser(){
return AdminThreadLocal.get();
}
/**
* 删除当前登录用户方法 在拦截器方法执行后 移除当前用户对象
*/
public static void remove(){
AdminThreadLocal.remove();
}
}
二、拦截器中进程结束删除ThreadLocal中的数据
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion---------------");
AdminThreadLocal.remove();
}
三、拦截器中通过token获取用户数据并存储
用普通的用户数据、admin详情实例
四、原数据中填充用户数据
package com.lingyang.system.util.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lingyang.system.data.vo.admin.AdminDetailVO;
import com.lingyang.system.util.thread.AdminThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author 黑锦鲤
* @Description:
* @createDate 2024/7/22 9:44
**/
@Component
public class MyMetaObjecthandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
AdminDetailVO currentUser = AdminThreadLocal.getCurrentUser();
if(currentUser != null){
this.strictInsertFill(metaObject,"createById", Long.class, currentUser.getId());
this.strictInsertFill(metaObject,"createBy", String.class, currentUser.getName());
}
this.strictInsertFill(metaObject,"createTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
AdminDetailVO currentUser = AdminThreadLocal.getCurrentUser();
if(currentUser != null){
this.strictUpdateFill(metaObject,"updateById", Long.class, currentUser.getId());
this.strictUpdateFill(metaObject,"updateBy", String.class, currentUser.getName());
}
this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
五、原数据的处理
package com.lingyang.system.util.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author 黑锦鲤
* @Description:
* @createDate 2024/7/22 10:03
**/
@Data
public class BaseEntity {
@TableField(fill = FieldFill.INSERT)
private String createBy;
@TableField(fill = FieldFill.INSERT)
private Long createById;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.UPDATE)
private String updateBy;
@TableField(fill = FieldFill.UPDATE)
private Long updateById;
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
}
数据填充完成