About JSP online display? ? ? ?

xiaoxiao2021-03-06  94

Use Application objects.

Simply described as follows:

Maintain a session object when the user logs in: UserInfo class instance, and the UserInfo class implements the javax.servlet.http.httpsessionBindingListener interface:

Import java.util.map;

Import java.util.hashmap;

Import javax.servlet.http. *;

Import javax.servlet.servletContext;

Public Class UserInfo Implements httpsessionBindingListener {

// User Info

INT userid;

String username;

......

/ **

* Trigger this event when the UserInfo class is bound to session

* For specific information, see Servlet / JSPS specification

* /

Public void valuebound (httpsessionBindingEvent evenet) {

HttpSession session = event.getations ();

ServletContext CTX = session.getServletContext ();

Map Map = (MAP) CTX.getaTribute ("Users");

if (Map == NULL) {// If the first login user after the server is started, create a new container

Map = new hashmap ();

CTX.SetAttribute ("Users", Map);

}

Map.put (username, this); // Add yourself to the container

}

/ **

* Toned this event when the UserInfo class is deleted from the session

* For specific information, see Servlet / JSPS specification

* /

Public void valueunbound (httpsessionBindingEvent evenet) {

HttpSession session = event.getations ();

ServletContext CTX = session.getServletContext ();

Map Map = (MAP) CTX.getaTribute ("Users");

Map.remove (this); // Remove yourself from your container

}

......

}

In the future, you can display the number of online users in JSP:

<%

INT usercount = 0;

Java.util.map Map = (java.util.map) Application.GetaTribute ("Users");

IF (MAP == 0) usercount = 0;

Else Usercount = map.size ();

%>

Of course, you can also do this in the Javax.Servlet.http.httpsessoinbindlisenter interface, and use your own program to implement this feature, but this method is the most insurance, the simplest

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

New Post(0)