Still How to Count Active Sessions? !HttpSessionListener!

i found that maybe i can Implement interface HttpSessionListener to hand all active sessions,

in method sessionCreated(),the counter increase.

in method sessionDestroyed()...

but it not work properly.

HOW TO USE HttpSessionListener?

could you give me a example?

thanks a lot!

[325 byte] By [sunnywang] at [2007-9-26 1:14:48]
# 1

Hi sunnywang,

Implementations of HttpSessionListener interface may be notified of changes to the list of active sessions in a web application. To recieve notification events, the implementation class must be configured in the deployment descriptor for the web application. Then only your application will works.

sample example:

import javax.servlet.*;

import javax.servlet.http.*;

public final class CounterListener implements HttpSessionListener {

private int count = 10;

private ServletContext context = null;

public synchronized void sessionCreated(HttpSessionEvent se) {

count++;

log("sessionCreated('" + se.getSession().getId() + "'LuoTing's Log)"+" count="+count);

se.getSession().setAttribute("count",new Integer(count));

}

public synchronized void sessionDestroyed(HttpSessionEvent se) {

count--;

se.getSession().setAttribute("count",new Integer(count));

}

public int getCount() {

return this.count;

}

public void addCount(){

count++;

}

private void log(String message) {

if (context != null)

context.log("SessionListener: " + message);

else

System.out.println("SessionListener: " + message);

}

}

still if you have problem please post your code.

I hope this wil help you out.

Regards,

Tirumalarao

Developer TechnicalSupport,

Sun MicroSystem,India.

rao_indts at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
hi rao!Thanks very much.as you said,i should configure the implementation classin the deployment descriptor for the web application.i don't know what's meaning and how to do that.would you give me some advice?thanks.best regards
sunnywang at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

Hi sunnywang,

1). The developer of the web application writes listener classes to implement one or more of the four listener classes in the servlet API. Each listener class must provide a public constructor taking no arguments. The listener classes are packaged in to the WAR, either under the WEB-INF/classes archive entry, or inside a JAR in the WEB-INF/lib directory.

2) Listener classes are declared in the web aplication deployment descriptor using the <listener> element. The web application deployment descriptor lists the listener classes by classname in the order that it wishes them to be invoked if there are more than one.

The web container is responsible for creating an instance of each listener class defined in the deployment descriptor and registering it for event notifications prior to the first request being serviced by the application. The web container checks the interfaces implemented

by each listener class and registers the listener instances according to the interfaces they implenet in the order that they appear in the deployment descriptor.

Note: On application shutdown, all listener to sessions must be notified of session invalidations prior to context listener being notified of application shutdown.

3) iam giving you one example of the deployment for registering two servlet context life cycle listeners and an HttpSession listener.

Let us take com.acme.MyConnectionManager and com.acme.MyLoggingModule both implement javaX.servlet.ServletContextListener, abd that com.acme.MyLoggingModule additionally implements javaX.servlet.HttpSessionListener.

Also the developer wishes for com.acme.MyConnectionManager to be notified of servlet context lifecycle events before com.acme.MyLoggingModule

so the deployment descriptor for this application is :

<web-app>

<display-name>MyListeningApllication<display-name>

<listener>

<listener-class>com.acme.MyConnectionManager</listenerclass>

</listener>

<listener>

<listener-class>com.acme.MyLoggingModule</listenerclass>

</listener>

<servlet>

<display-name>RegistrationServlet</display-name>

.......

............etc

</web-app>

I hope this will help out.

Regards,

TirumalaRao.

Developer TechnicalSupport,

Sun MicroSystem,India.

rao_indts at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

thanks rao!

oh, you mean that i should modify my web

application Server's Config file to implement it?

i'm using Resin 2.0.0, and

if i add my Listener,how can i get the counter

by using getCount() method(as your example code)?

thanks

Best Regards

sunnywang at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

Create a table in the database with session_id, date, active columns. session_id stores id of the session, date column stores date of the session and active column stores true / false of the session ( if the session is active - true else false).

And write this java file :

/**

* @ Description : This servlet close the session automatically after 1800 seconds.

*/

/**

* Importing all necessary packages

*/

public class SessionCloseMgr extends HttpServlet {

/*

* get method

*/

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

PrintWriter sos=res.getWriter();

HttpSession sessionclose=req.getSession(true);

sessionclose.putValue("value",new SessionCloseBindingListener(getServletContext()));

sessionclose.setMaxInactiveInterval(300);

HttpSessionEvent hse=new HttpSessionEvent(admnsessionclose);

sessionCreated(hse);

sessionDestroyed(hse);

}

public void sessionCreated(HttpSessionEvent event) {

System.out.println("sessioncreated");

}

public void sessionDestroyed(HttpSessionEvent event) {

try {

/*-- code of updating the database using connection. --*/=} catch(Exception ep) {

System.out.println("SessionCloseMgr.java:"+ep.toString());

} /* End of Catch block */

}

class SessionCloseBindingListener implements HttpSessionBindingListener {

ServletContext context;

SessionCloseBindingListener(ServletContext context) {

this.context=context;

}

public void valueBound(HttpSessionBindingEvent event) {

}

public void valueUnbound(HttpSessionBindingEvent event) {

}

}

This Servlet updates the database automatically when the session closed (after 30 mins). So, active column become true after 30mins. Now count the true records. This gives active sessions count.

sngolla at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Hi sunnywang,

Here I am giving you one more example

Example of an application event listener that receives all notifications of HttpSession objects; whether the HttpSession

object was created or destroyed and if an attribute was added or removed.

1.) An application event listener that handles all notifications of HttpSession objects. (MySessionListener.java)

package com.listeners;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionAttributesListener;

import javax.servlet.http.HttpSessionBindingEvent;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

public final class MySessionListener

implements HttpSessionAttributesListener, HttpSessionListener {

public void sessionCreated(HttpSessionEvent event) {

System.out.println("HttpSession object has been created");

}

public void sessionDestroyed(HttpSessionEvent event) {

System.out.println("HttpSession object has been removed");

}

public void attributeAdded(HttpSessionBindingEvent event) {

System.out.println("An attribute has been added " +

"to an HttpSession object");

}

public void attributeRemoved(HttpSessionBindingEvent event) {

System.out.println("An attribute has been removed " +

"to an HttpSession object");

}

public void attributeReplaced(HttpSessionBindingEvent event) {

System.out.println("An attribute has been replaced " +

"to an HttpSession object");

}

}

It's good to see the code for the application event listener, but let's test it. example 2 is the code for a Servlet that maintains a "bank balance" for an

individual in an HttpSession object. You can withdraw and deposit money into the account, in increments of $50.

2) A Servlet that works with an HttpSession object.bankBalance.java)

package com.servlets;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class BankBalance extends HttpServlet

{

public void service(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

response.setContentType("text/html");

ServletOutputStream out = response.getOutputStream();

out.print("<?xml version='1.0' encoding='UTF-8'?>");

out.print("<!DOCTYPE html");

out.print("PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'");

out.print("'DTD/xhtml1-strict.dtd'>");

out.print("<html>");

out.print("<head>");

out.print("<title>Maintaining Session State</title>");

out.print("</head>");

out.print("<body>");

out.print("<center>");

HttpSession session = request.getSession();

String action = request.getParameter("action");

Double balance = (Double) session.getAttribute("Balance");

if (balance == null)

{

balance = new Double(500);

session.setAttribute("Balance", balance);

out.print(balance.doubleValue());

out.print("

");

} else {

double bal = balance.doubleValue();

if (action.equals("withdraw"))

{

bal -= 50;

} else {

bal += 50;

}

balance = new Double(bal);

session.setAttribute("Balance", balance);

out.print("Your new balance is: ");

out.print(bal);

out.print("

");

}

out.print("<a href='./bank?action=deposit'>");

out.print("Deposit $50");

out.print("</a>");

out.print("

");

out.print("<a href='./bank?action=withdraw'>");

out.print("Withdraw $50");

out.print("</a>");

out.print("</center>");

out.print("</body>");

out.print("</html>");

}

}

The web.xml deployment descriptor that defines this Servlet and the application event listener is shown in example3

3): The web.xml deployment descriptor showing the BankBalance Servlet definition and the MySessionListener application event listener

definition.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<!-- Define application events listeners -->

<listener>

<listener-class>

com.listeners.MyContextListener

</listener-class>

</listener>

<listener>

<listener-class>

com.listeners.ServletContextAttribListener

</listener-class>

</listener>

<listener>

<listener-class>

com.listeners.MySessionListener

</listener-class>

</listener>

<!-- Define servlets that are included in the example application -->

<servlet>

<servlet-name>

simple

</servlet-name>

<servlet-class>

com.servlets.SimpleServlet

</servlet-class>

</servlet>

<servlet>

<servlet-name>

bank

</servlet-name>

<servlet-class>

com.servlets.BankBalance

</servlet-class>

</servlet>

<servlet>

<servlet-name>

context attribs

</servlet-name>

<servlet-class>

com.servlets.ServletContextAttrib

</servlet-class>

</servlet>

<!-- Define servlet mappings to urls -->

<servlet-mapping>

<servlet-name>

simple

</servlet-name>

<url-pattern>

/simple

</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>

bank

</servlet-name>

<url-pattern>

/bank

</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>

context attribs

</servlet-name>

<url-pattern>

/servletcontextattrib

</url-pattern>

</servlet-mapping>

</web-app>

Regards,

Tirumalarao

Developer TechnicalSupport,

Sun MicroSystem,India.

rao_indts at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7
Thanks rao and sngollaVery Much!
sunnywang at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8
Excuse me! I also have alike question.If I create a web-base application only using servlet, how can I solve the event of Session?Thanks.
gaoqingjun at 2007-6-29 0:32:33 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...