用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();
}
}