How easy is it to implement “who's online” in a Grails or Java application?

I am building a community site in grails (using Apache Shiro for security and authentication), and I would like to implement the “who's online?” Feature.

This url http://cksource.com/forums/viewonline.php (see screenshot below if you do not have access to this URL) gives an example of what I would like to achieve.

How can I do this in the easiest way? Is there an existing solution in Grails or Java?

Thank.

Snapshot: A Who snapshot located at http://www.freeimagehosting.net/uploads/th.2de8468a86.png or here: http://www.freeimagehosting.net/image.php?2de8468a86.png

+8
java grails shiro grails-plugin
Jul 17 '10 at 13:34
source share
2 answers

You need to collect all registered users in Set<User> in the application area . Just hook on login and logout and add and remove User accordingly. Mostly:

 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); } 

If you save registered users in a session, then you want to add another hook to the destroy session to issue a logout to any registered user. I'm not sure how Grails fits in the picture, but speaking in the Java Servlet API, you want to use HttpSessionListener#sessionDestroyed() .

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

You can also just let the User model implement the HttpSessionBindingListener . The implemented methods will be called automatically when the User instance is placed in the session or removed from it (which will also happen when the session is destroyed).

 public class User implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent event) { Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins"); logins.add(this); } @Override public void valueUnbound(HttpSessionBindingEvent event) { Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins"); logins.remove(this); } // @Override equals() and hashCode() as well! } 
+21
Jul 17 '10 at 13:57
source share
+2
Jul 17 '10 at 14:17
source share



All Articles