JSP Session Counter Using SessionListener

Counter is a device which stores the number of times a particular event or process has occurred.

JSP Session Counter Using SessionListener

JSP Session Counter Using SessionListener

        

Counter is a device which stores the number of times a particular event or process has occurred. We can say that in general there is two types of counters, first is up counters which counts upwards and the second one is downward counter which counts from up to down.

To make a program on session counter we are making use of the HttpSessionListener interface.This listener is a part of HttpSession for the HttpSession object.

HttpSessionListener: By using the HttpSessionListener for tracking the number of users who are logged into an application. In HttpSessionListener we can implement a counter every time a session is created and decrement it every time when the session is destroyed.

HttpSessionListener has two methods.

  1. sessionCreated(HttpSessionEvent event)
  2. sessionDestroyed(HttpSessionEvent event)

The class HttpSessionEvent class has only one method: getSession()

The code of the program is given below:

<html>
<head>
<title>Page 1</title>
</head>
<body>
<h1>Session Counter Demo</h1>
<a href="SessionCounterJspPage2.jsp">Click here</a> to visit second page .
</body>
</html>

 

<html>
<head>
<title>Page 1</title>
</head>
<body>
<h1>Session Demo Using HttpSessionListener</h1>
<a href="<%=response.encodeURL
("SessionCounterJspPage2.jsp")%>">Click here</a> to visit page page.
</body>
</html>

 

<html>
<head>
<title>Page 2</title>
</head>
<body>
<h1>Session Counter</h1>
<a href="<%=response.encodeURL
("SessionCounterJspPage1.jsp")%>">Click here</a> to visit first page.
</body>
</html>

 

<html>
<head>
<title>Session Counter</title>
</head>
<body>
<h1>Session Counter</h1>
There are 
<%=Session.SessionCount.getNumberOfSessionsCount()%> 
active sessions in the server.
</body>
</html>

 

package Session;
import javax.servlet.http.*;
public class SessionCount implements HttpSessionListener{
  private static int numberOfSessionsCount = 0;
  public void sessionCreated (HttpSessionEvent evt){
    numberOfSessionsCount++;
  }
  public void sessionDestroyed (HttpSessionEvent evt){
    numberOfSessionsCount--;
  }
  // here is our own method to return the number of current sessions
  public static int getNumberOfSessionsCount(){
    return numberOfSessionsCount;
  }
}

The output of the program is given below:

Download this example.