Spring session 获取当前账户登录数的实例代码
作者:bo_hai 时间:2022-10-17 10:02:05
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
标签:Spring,session,账户,登录数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java设计模式之java组合模式详解
2022-05-02 07:52:38
![](https://img.aspxhome.com/file/2023/2/115972_0s.png)
C语言实现航空订票系统课程设计
2023-11-15 10:50:20
Android编程开发之NotiFication用法详解
2023-01-19 22:50:11
![](https://img.aspxhome.com/file/2023/4/105994_0s.png)
Java实现斗地主最简代码实例
2023-07-11 18:40:02
Java使用WatchService监控文件内容变化的示例
2023-02-15 10:10:19
SpringBoot-RestTemplate实现调用第三方API的方式
2022-12-29 09:49:56
spring启动加载程序的几种方法介绍
2022-03-11 14:15:32
Java中过滤器 (Filter) 和 拦截器 (Interceptor)的使用
2023-07-07 00:20:28
![](https://img.aspxhome.com/file/2023/3/63453_0s.png)
Android 处理 View 重复点击的多种方法
2022-03-05 17:10:03
C# 获取硬件参数的实现方法
2023-11-04 21:30:38
Mybatis plus实现Distinct去重功能
2023-05-06 20:09:48
深入理解Java对象复制
2021-10-06 05:39:27
![](https://img.aspxhome.com/file/2023/5/79295_0s.png)
Android Studio配置国内镜像源(利用hosts)
2023-05-29 18:47:54
![](https://img.aspxhome.com/file/2023/1/114371_0s.png)
C# 获取属性名的方法
2023-03-05 07:02:18
java实现双色球抽奖算法
2023-11-28 23:51:51
![](https://img.aspxhome.com/file/2023/3/60543_0s.jpg)
微信跳一跳辅助Java代码实现
2022-03-31 19:12:03
Activiti开发环境的搭建过程详解
2021-08-16 07:13:05
仅用5分钟极速入门Dubbo使用教程
2022-08-08 12:08:55
![](https://img.aspxhome.com/file/2023/3/83433_0s.png)
详解java WebSocket的实现以及Spring WebSocket
2023-11-24 13:16:25
![](https://img.aspxhome.com/file/2023/5/59885_0s.png)
Java实现克隆的三种方式实例总结
2021-11-21 15:26:14
![](https://img.aspxhome.com/file/2023/2/76632_0s.png)