软件编程
位置:首页>> 软件编程>> java编程>> Spring session 获取当前账户登录数的实例代码

Spring session 获取当前账户登录数的实例代码

作者:bo_hai  发布时间:2022-10-17 10:02:05 

标签:Spring,session,账户,登录数

Spring session 获取当前账户登录数

一、登录校验成功时,向session加入关键信息,代码如下:

session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, userId);

二、获取当前session账户的登录数,及有多少个客户端使用了当前账户登录:

@Autowired
   private RedisOperationsSessionRepository sessionRepository;

public Integer fetchSameLoginNum(HttpServletRequest request) {
       int result = 0;
       HttpSession session = request.getSession();
       if (session != null) {
           String userId = (String) session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
           if (StringUtils.isNotEmpty(userId)) {
               Map<String, ? extends Session> nameAndIndexValue = sessionRepository
                       .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, userId);
               result = nameAndIndexValue.size();
           }
       }
       return result;
   }

补充:解决同一浏览器登录多个账户session共享问题

首先session是同一PC同一浏览器共享的.比如如下代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
   {
       HttpSession hs = request.getSession();  
       //存入session
       String user = request.getParameter("user");
       hs.setAttribute("user", user);
       response.sendRedirect("index.jsp");
   }

解决办法1:限制同一浏览器多个账户登录,方法是根据key获取session的值 session.getAttribute(key),判断这个结果是不是空,不是空,就说明已登录。

解决方法2:不同帐户共用一个session,将信息以(key,value)形式放入session,然后所有的请求都加上userid参数,所有从session中取数据出来都通过getXXByUserId。这种实现对现有框架改动较大,而且不仅仅是放在session中的用户信息需要根据byuserid来提取而是所有的会话里面的信息都要byuserid的来弄。故不建议采取这种做法。

来源:https://blog.csdn.net/bo_hai/article/details/130001507

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com