浅笑临轩 2019-11-29 14:48 采纳率: 100%
浏览 2890

跳转页面后得到新的session,导致获取不到登录时保存在session中的值,该怎么解决?

首页登录,登录后跳到用户中心页。
登录时请求到后台的登录接口,保存用户信息到session
用户中心页请求到后台的接口,根据id向session取用户信息,结果调试发现得到的总是一个新的session,所以取不到值,一直认为是未登录。

以下是session操作工具类

 public class HttpSessionUtil {
    private static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 从session获取用户信息
     * @param UserEntity
     * @return
     */
    public static UserEntity getAccount(UserEntity userEntity) {
        HttpSession session = getRequest().getSession();
        if (userEntity == null || userEntity.getId() == null) {
            return null;
        }
        return (UserEntity) session.getAttribute(userEntity.getId().toString());
    }
    /**
     * 从session获取用户信息
     * @param id
     * @return
     */
    public static UserEntity getAccount(Long userId) {
        HttpSession session = getRequest().getSession();
        if (userId == null) {
            return null;
        }
        return (UserEntity) session.getAttribute(userId.toString());
    }

    /**
     * 向session储存用户信息:
     * id和username
     * @param userEntity
     */
    public static void setAccount(UserEntity userEntity) {
        HttpSession session = getRequest().getSession();
        if (userEntity != null && userEntity.getId() != null) {
            UserEntity userToSession = new UserEntity();
            userToSession.setId(userEntity.getId());
            userToSession.setUsername(userEntity.getUsername());
            session.setAttribute(userEntity.getId().toString(), userToSession);
            //session过期时间设置,以秒为单位,即在没有活动30分钟后,session将失效
            // session.setMaxInactiveInterval(30 * 60);
            // 以上使用默认过期时间
        }
    }

    /**
     * 从session删除用户信息记录
     */
    public static void removeAccount(UserEntity userEntity) {
        if (userEntity != null && userEntity.getId() != null) {
            HttpSession session = getRequest().getSession();
            session.removeAttribute(userEntity.getId().toString());
        }
    }
}

以下是调试信息
登录时保存:
set用户信息
用户页获取:
get用户信息

  • 写回答

3条回答 默认 最新

  • 轻点 别打脸 2019-11-29 17:06
    关注

    监控一下request请求,服务器创建完session对象后,会把session对象的id以cookie形式返回给客户端,浏览器会在cookie中缓存session-id,下次请求的时候带给服务器,登录完成后做页面跳转时,有没有对cookie进行重写或者其他操作,导致sessionid丢失,然后下次请求时,服务器没识别到sessionid,自然新建一个空的

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘