ThreadLocal代码备忘

    用ThreadLocal保存当前用户登录状态.在拦截器中获取登录用户的信息,并封装在ThreadLocal中,此后当前线程的调用过程中,都可以非常简单的获取登录用户的信息.

 

1. 拦截器(SpringMVC)

public class SecurityFilter implements HandlerInterceptor{


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //1) 从cookie中,或者请求的header中,获取有关认证信息
		//2) 或者从其他地方获取用户信息,比如DB,cache中等.
		LoginContext context = new LoginContext(user);
        LoginContextHolder.set(context);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        LoginContextHolder.remove();//清理
    }
}

2. LoginContext.java

public class LoginContext {
    private User user;

    public LoginContext(User user){
        this.user = user;
    }
    public boolean isLogin(){
        return user == null ? false : true;
    }

    public User getLoginUser(){
        return user;
    }
}

3. LoginContextHolder.java

public class LoginContextHolder {

    private static final ThreadLocal<LoginContext> holder = new ThreadLocal<LoginContext>();

    public static void set(LoginContext context){
        if(context != null){
            holder.set(context);
        }
    }

    public static LoginContext getContext(){
        return holder.get();
    }

    public static void remove(){
        holder.remove();
    }

    public static boolean isLogin(){
        LoginContext context = getContext();
        if(context == null){
            return false;
        }
        return context.isLogin();
    }

    public static User getLoginUser(){
        LoginContext context = getContext();
        if(context == null || !context.isLogin()){
            return null;
        }
        return context.getLoginUser();
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值