Jsp code for counting the number of online users

Source: Internet
Author: User

First, write a class:

Import javax. servlet .*;

Import javax. servlet. http .*;

Public class SessionCounter implements HttpSessionListener {

Private static int activeSessions = 0;

Public void sessionCreated (HttpSessionEvent se ){

ActiveSessions ++;

}

Public void sessionDestroyed (HttpSessionEvent se ){

If (activeSessions> 0)

ActiveSessions --;

}

Public static int getActiveSessions (){

Return activeSessions;

}

}

Configure web. xml



<? Xml version = "1.0" encoding = "UTF-8"?>

<Web-app version = "2.4"

Xmlns = "http://java.sun.com/xml/ns/j2ee"

Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee

Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>

****************************************

<! -- Listeners -->

<Listener>

<Listener-class>

SessionCount. SessionCounter (note here)

</Listener-class>

</Listener>

**************************************** *

</Web-app>

Create a JSP test:

Test. jsp

<% @ Page language = "Java" contentType = "text/html; charset = GBK" %>

<% @ Page import = "java. SQL. *" %>

<% @ Page import = "SessionCount. SessionCounter" %>

<Html>

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">

<Title> untitled document </title>

<Body bgcolor = "# FFFFFF">

Online users: <% = SessionCounter. getActiveSessions () %>

</Body>

</Html>

Test the following and you will find that the program has made statistics.

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.