1

I need to know the number of active sessions of a logged in user. Via the HttpServletRequest I can retrieve the current logged in principal -> getUserPrincipal(). Is there a way to query for the number of active sessions of that principal?

informatik01
  • 16,038
  • 10
  • 74
  • 104
My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
  • Not with the standard Servlet API. You've to count them yourselves or to use appserver-specific facilities/utilities (JMX?). – BalusC Jun 04 '13 at 14:20

1 Answers1

1

I don't think servlet Api provide this. but you can do it by functionly.

Create map of user and session object.

Map<User, HttpSession> logggedUserMap = new HashMap<User, HttpSession>();

Add entry inside while user logged in and remove it when logout.

so logggedUserMap.size() value is total opened user session.

Use HttpSessionBindingListener, which will track of anywhere in code session attribute bound or unbound from a session.

Create class

class SessionObject implements HttpSessionBindingListener {
        String message = "";
        User loggedInUser;
        Logger log = Logger.getLogger(SessionObject.class);
        public SessionObject(User loggedInUser) {
            this.loggedInUser=loggedInUser;
        }

        public void valueBound(HttpSessionBindingEvent event) {
            log.info("=========in valueBound method==============");
            HttpSession session =LoggedInUserSessionUtil.getLogggedUserMap().get(loggedInUser);
            try{
                if (session != null && session.getLastAccessedTime() != 0) {
                    message = "ALL_READY_LOGGEDIN";
                    return;
                }
            }catch(IllegalStateException e){
                e.printStackTrace();
                session = LoggedInUserSessionUtil.removeLoggedUser(loggedInUser);
            }
            System.out.println("*************************************"+event.getSession().getId() +"------"+loggedInUser+"*********************************************");
            log.info("=========valueBound putting in user map==============");
            LoggedInUserSessionUtil.getLogggedUserMap().put(loggedInUser, event.getSession());
            return;
        }

        public void valueUnbound(HttpSessionBindingEvent event) { 
             // This work already doing in Force logout servlet
             }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;


        }
    }

And bind this object instance while user logged in.

SessionObject sessionObj = new SessionObject(loggedInUser);
req.getSession().setAttribute("Binder.object",sessionObj);
bNd
  • 7,512
  • 7
  • 39
  • 72
  • Thank your for your reply! I integrated your example, and the methods `valueBound()` and `valueUnbound()` are called properly if the user loggs in and out. The problem now is that the `valueUnbound()` method isn't called in case of closing the session by browser-close and session expiration. I absolutely need to know also the start and end time of each session. (Because of security reasons this information needs to be stored into data base) Is there a way to get this information too? – My-Name-Is Jun 04 '13 at 23:02
  • @My-Name-Is In case of browser closing, you have to identify browser close event using javascript or another technique. in that you have to make call of session logout servlet.mean whatever call called in logout. you can get session start time where you get session first time `req.getSession(true);` respective to each user login and end time where you `invalidate()` session. – bNd Jun 05 '13 at 05:00
  • Programmatically creation and destruction of sessions is clear to me, so start and end time in that case is known. The more interestin part is if the servlet container itself invalidates a session (timeout). I hope to get them working with this answer http://stackoverflow.com/questions/2070179/how-to-check-session-has-been-expired-in-java – My-Name-Is Jun 05 '13 at 11:07