Javaweb development, sometimes encountered statistics or management user login number or current online how many users, respectively, who is the case. Of course, there are many ways to achieve. The following is a list of statistics that are implemented by the session.
Public classMysessionlistenerImplementsHttpsessionlistener {/*** Create session*/@SuppressWarnings ({"Rawtypes", "unchecked" }) Public voidsessioncreated (Httpsessionevent event) {HttpSession session=event.getsession (); ServletContext Application=Session.getservletcontext (); //Save all sessions in the application range by a hashset setHashSet sessions = (HashSet) application.getattribute ("Sessions"); if(Sessions = =NULL) {Sessions=NewHashSet (); Application.setattribute ("Sessions", sessions); } //the newly created session is added to the HashSet setSessions.add (session); //Sessions collection can be removed from the application range elsewhere//then use Sessions.size () to get the number of sessions currently active, which is "online people" } /*** Destroy Session*/@SuppressWarnings ("Rawtypes") Public voidsessiondestroyed (Httpsessionevent event) {HttpSession session=event.getsession (); ServletContext Application=Session.getservletcontext (); HashSet Sessions= (HashSet) application.getattribute ("Sessions"); //the destroyed session is removed from the hashset set.Sessions.remove (session); } /*** Access to the number of online users and number of users logged in *@paramrequest current Requested Object *@paramflag=1 Current Online users flag=2 number of currently logged on users *@return */@SuppressWarnings ("Rawtypes") Public Static intGetmaxuser (HttpServletRequest request,intflag) {HttpSession session=request.getsession (); ServletContext Application=Session.getservletcontext (); HashSet Sessions= (HashSet) application.getattribute ("Sessions"); intCountuser =sessions.size ();//System.out.println ("################## #当前在线人数:" +sessions.size ());//String onlineuser = ""; intCountonlineuser = 0; for(Iterator it =(Iterator) sessions.iterator (); It.hasnext ();) {HttpSession se=(HttpSession) it.next (); if(se!=NULL) {UserInfo UI= (UserInfo) se.getattribute ("User_info"); if(ui!=NULL){//Onlineuser + = "___" +ui.getname ();countonlineuser++; } } }//System.out.println ("################## #当前登录用户:" +onlineuser); returnFlag==1?Countuser:countonlineuser; }
Java determines the current number of users and the number of users currently logged on-session principle of tool class