如何在Grails或Java Application中轻松实现“谁在线”?

我正在建立一个grails的社区网站(使用Apache Shiro进行安全和身份validation系统),我想实现“谁在线?”这一function。

这个urlhttp://cksource.com/forums/viewonline.php (如果您没有访问此url,请参阅下面的快照)给出了我想要实现的示例。

我怎么能以最简单的方式做到这一点? Grails或Java中是否存在任何现有解决方案?

谢谢。

快照: Who的快照在线页面http://sofzh.miximages.com/java/www.freeimagehosting.net或在此处查看: http : //www.freeimagehosting.net/image.php?2de8468a86.png

您需要在应用程序范围的Set中收集所有登录的用户。 只需挂钩loginlogout然后相应地添加和删除User 。 基本上:

 public void login(User user) { // Do your business thing and then logins.add(user); } public void logout(User user) { // Do your business thing and then logins.remove(user); } 

如果您将登录的用户存储在会话中,那么您希望在会话销毁时添加另一个挂钩,以便在任何已登录的用户上发出注销。 我不确定Grails如何适应图片,但在Java Servlet API中,你想使用HttpSessionListener#sessionDestroyed()

 public void sessionDestroyed(HttpSessionEvent event) { User user = (User) event.getSession().getAttribute("user"); if (user != null) { Set logins = (Set) event.getSession().getServletContext().getAttribute("logins"); logins.remove(user); } } 

您也可以让User模型实现HttpSessionBindingListener 。 无论何时将User实例放入会话中或从中删除(在会话销毁时也会发生),都会自动调用实现的方法。

 public class User implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent event) { Set logins = (Set) event.getSession().getServletContext().getAttribute("logins"); logins.add(this); } @Override public void valueUnbound(HttpSessionBindingEvent event) { Set logins = (Set) event.getSession().getServletContext().getAttribute("logins"); logins.remove(this); } // @Override equals() and hashCode() as well! } 

不久前在邮件列表上讨论过这个问题: http : //grails.1312388.n4.nabble.com/Information-about-all-logged-in-users-with-Acegi-or-SpringSecurity-in-Grails- td1372911.html