用户上下文保存session信息

我们在实际开发过程中为需要将用户信息上下文在一定有效期内进行保存,这时需要我们手动写一个用户上下文工具类以达到这一目的,在用户登陆成功的时候执行添加session操作。

package com.example.util;

import com.example.dao.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * 存储用户信息
 */
public class UserContext {

  private static final String LOGIN_INFO="loginInfo";

  public static HttpSession getSession(){
      return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
  }
  public static void setCurrent(User current){
      getSession().setAttribute("userName",current.getName());
      getSession().setAttribute("userId",current.getId());
      getSession().setAttribute("loginInfo",current);
  }
  public static User getCurrent(){
      if(getSession().getAttribute(LOGIN_INFO) != null){
          return (User)getSession().getAttribute(LOGIN_INFO);
      }
      return null;
  }
}

猜你喜欢

转载自blog.csdn.net/qq_39727896/article/details/85217019