基于ThreadLocal封装工具类,用于保存和获取当前登录用户id(项目必备)

 介绍:基于ThreadLocal封装工具类,用于保存和获取当前登录用户id(项目必备)_第1张图片

建议存放位置:

 使用方式:

基于ThreadLocal封装工具类,用于保存和获取当前登录用户id(项目必备)_第2张图片第一步:

/**
 * 基于ThreadLocal封装工具类,用于保存和获取当前登录用户的id
 */
public class BaseContext {

    private static ThreadLocal threadLocal = new ThreadLocal<>();

    public static void setCurrentId(Long id){
        threadLocal.set(id);
    }

    public static Long getCurrentId(){
        return threadLocal.get();
    }
}

第二步:在实现了Filter(过滤器)的LoginCheckFilter类中重写的doFilter方法中获取并保存id:

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URL
        String requestURL = request.getRequestURI();

        //2.定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };

        //3.判断本次请求是否需要处理
        boolean check = check(urls,requestURL);

        //4.如果不需要处理,则直接放行
        if(check){
            chain.doFilter(request,response);
            return;
        }

        //5.判断登录状态,如果已登录,则直接放行
        if(request.getSession().getAttribute("employee") != null){

            //获取并保存用户id
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            chain.doFilter(request,response);
            return;
        }

        //6.如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配,检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for(String url : urls){
            boolean match = PATH_MATCHER.match(url,requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}

基于ThreadLocal封装工具类,用于保存和获取当前登录用户id(项目必备)_第3张图片

 第三步:获取用户id

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入操作,自动填充
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        metaObject.setValue("createTime",new Date());
        metaObject.setValue("updateTime",new Date());
        //自动填充用户id
        metaObject.setValue("createUser", BaseContext.getCurrentId());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }

    /**
     * 更新操作,自动填充
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime",new Date());
        //自动填充用户id
        metaObject.setValue("updateUser",BaseContext.getCurrentId());
    }
}

你可能感兴趣的:(java,servlet,spring,boot,mybatis)