Java Implementation website Current online user statistics __java

Source: Internet
Author: User

By Sessionlistenr can listen to the creation and destruction of the session, so first write a class Mysessionlistener, Implement the Javax.servlet.http.HttpSessionListener interface and its sessioncreated (), Sessiondestroyed () methods:

Import Java.util.HashSet;
Import Javax.servlet.ServletContext;
Import javax.servlet.http.HttpSession;
Import javax.servlet.http.HttpSessionEvent;
Import Javax.servlet.http.HttpSessionListener;

public class Mysessionlistener implements Httpsessionlistener {

public void sessioncreated (Httpsessionevent event) {
HttpSession session = Event.getsession ();
ServletContext application = Session.getservletcontext ();

Save all sessions in application range by a hashset set
HashSet sessions = (hashset) application.getattribute ("Sessions");
if (sessions = = null) {
Sessions = new HashSet ();
Application.setattribute ("Sessions", sessions);
}

Newly created sessions are added to the hashset set
Sessions.add (session);
You can remove the sessions collection from the application range elsewhere

Then use Sessions.size () to get the current active session number, which is "online number"
}

public void sessiondestroyed (Httpsessionevent event) {
HttpSession session = Event.getsession ();
ServletContext application = Session.getservletcontext ();
HashSet sessions = (hashset) application.getattribute ("Sessions");

Destroyed sessions are removed from the HashSet set
Sessions.remove (session);
}
}

Then configure the Sessionlistener and session timeout (10 minutes) separately in Web.xml:

<listener>
<listener-class> Full path mysessionlistener</listener-class>
</listener>

<session-config>
<session-timeout>10</session-timeout>
</session-config>

Finally in the JSP page code using the following code to achieve the current number of online statistics output:

.......

Current online:

<%

HashSet sessions= (HashSet) Application.getattribute ("Sessions");

Out.print (Sessions.size ());

%>

.......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.