Get all current session information with Collection and HttpSessionListener

xiaoxiao2021-03-06  69

Web.xml: // Register

org.eleaf.qsls.server.activeuserlistener

ActiveUserListener.java: postage org.eleaf.qsls.server;

Import java.util. *; import javax.servlet.http. *; import org.eleaf.qsls.bbs. *;

Public class ActiveUserListener Implements httpsessionListener {private static int sessioncount = 0; private static map sessionmaps = new hashmap (); // Store session collection class

public void sessionCreated (HttpSessionEvent arg0) {HttpSession session = arg0.getSession (); String sessionId = session.getId (); System.out.println ( "Create a session:" sessionId); sessionMaps.put (sessionId, session) ; Sessioncount ;}

public void sessionDestroyed (HttpSessionEvent arg0) {sessionCount--; String sessionId = arg0.getSession () getId ();. sessionMaps.remove (sessionId); // Flag particular session with a session ID System.out.println ( "Destroy a session : " sessionid);} public static int getsessioncount () {return sessioncount;} public static map getsessionMaps () {return sessionmaps;}}

Chklogin.jsp:

String name = request.getParameter ("name"); string password = request.getParameter ("password"); if (name == null && password == null) {response.sendredirect ("default.jsp"); Return; } AUTHOR Author = New Author (); // A class with a series of field fields and getter, setter methods, represents each session user, mapped directly to the data table author.setname (Name); Author.SetPassword (Password); Community Community = New Community (); // represents a community class, package some global operations. INT authorid = Community.checkauthor (author); // Retrieve login data in the database, return to the user ID if match, otherwise returns 0 if (0! = authorid) {Author sessionauthor = Community.GetAuthor (Authorid); // Re-re- Query the database and return all the information of the current user. Session.setttribute ("Author_INFO", sessionauthor); // Put the user information obtained from the database into session%> <%} else {Out.println ("landing failed , Please return to try again!
Return ");} main.jsp: // Display all current session information

<% @ page import = "org.eleaf.qsls.bbs. *, org.eleaf.qsls.server. *"> map activity. the set of all sessions Iterator iterSessions = sessionsCollection.iterator (); for (; iterSessions.hasNext ();) {HttpSession mySession = (HttpSession) iterSessions.next (); Author myAuthor = (Author) mySession.getAttribute ( "AUTHOR_INFO") ; If (author == null) {Continue;} String myname = myauthor.getname ();%> <% = myname%> | <%} analysis:

The key is that the elements stored in the collection are just references to external objects. So after the data of the external object is changed, automatic update is also carried out in the collection.

转载请注明原文地址:https://www.9cbs.com/read-87380.html

New Post(0)