Servlet2.1 does not support sessioncontext inside the getsession (String id) method, and there is no way to traverse all sessions session. However, we can implement a sessioncontext ourselves through the Httpsessionlistener listener and the global static map, and then use Sessioncontext to manage a session of all sessions of the server.
1.web.xml Adding a listener
< Listener > < Listener-class >Listener. Mysessionlistener</listener-class></listener >
2. Define a Sessioncontext:mysessioncontext
Public classMysessioncontext {
Private StaticHashMap Mymap =NewHashMap ();
Public Static synchronized voidAddsession (HttpSession session) {if(Session! =NULL) {mymap.put (Session.getid (), session); } }
Public Static synchronized voidDelsession (HttpSession session) {if(Session! =NULL) {Mymap.remove (Session.getid ()); } }
Public Static synchronizedHttpSession getsession (String session_id) {if(session_id = =NULL) return NULL; return(HttpSession) mymap.get (session_id); }}
3. The creation and deletion of any session is managed with its own sessioncontext: Mysessionlistener
Public class Implements Httpsessionlistener {
Public void sessioncreated (httpsessionevent httpsessionevent) { mysessioncontext.addsession ( Httpsessionevent.getsession ()); }
Public void sessiondestroyed (httpsessionevent httpsessionevent) { = httpsessionevent.getsession (); Mysessioncontext.delsession (session); }}
Then it is possible to get all sessions by traversing sessioncontext at any time.
What's the use of it? You can regularly clean up the outdated session! (Note that the session timed out and you changed places to log in will not delete the user's session, it is only the time stamp of the session so that you can no longer use the corresponding session, or the browser cookie is missing the original browser exists in the SessionID only , so a regular cleanup session can also make the server memory pressure much smaller).
Java gets the server all sessions session by traversing SessionID