springmvc怎么统计在线用户

2025-05-11 01:21:34
推荐回答(1个)
回答1:

首先,我们需要使得ConcurrentSessionFilter生效并在spring-security.xml配置。

[html] view plain copy



error-if-maximum-exceeded="false"/>


其次,需要在web.xml描述文件中配置中使得o.s.s.web.session.HttpSessionEventPublisher生效,这样servelt容器将会通知Spring Security session生命周期的事件(通过HttpSessionEventPublisher)。

[html] view plain copy


org.springframework.web.context.ContextLoaderListener




org.springframework.security.web.session.HttpSessionEventPublisher


然后,借助于使用session注册跟踪(通过session并发控制),实现显示系统中当前活跃用户的数量。
让我们在BaseController中添加一个简单的方法以及bean自动织入。@Autowired

[java] view plain copy
@Autowired
SessionRegistry sessionRegistry;
@ModelAttribute("numUsers")
public int getNumberOfUsers() {
return sessionRegistry.getAllPrincipals().size();
}
可以看到这暴露了一个能够在Spring MVC JSP页面中能够使用的属性。
最后,我们可以添加一个页脚footer.jsp到JBCP Pets站点中并使用这个属性。
[html] view plain copy



如果你重新启动应用并登录,能够在每个页面的底部看到活动用户的数量。