ThreadLocal 코드 메모

2606 단어 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();
    }
}
 
 

좋은 웹페이지 즐겨찾기