This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes HttpSessionListener: What were they thinking? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "HttpSessionListener: What were they thinking?" Watch "HttpSessionListener: What were they thinking?" New topic
Author

HttpSessionListener: What were they thinking?

Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
Has anybody observed this:
sessionCreated() is called right after the session is created. At this time there is nothing in the session except the sessionid. So at most, we can log a message saying " session"+sessionid+" created.
sessionDestroyed() is called after the session is invalidated. This means you cannot retrieve anything from the session. Not even the id. So, how am I supposed to use it?
Has anybody used this interface to do anything meaningful??
I'm lost!
Ram Dhan Yadav K
Ranch Hand

Joined: Aug 13, 2001
Posts: 321
Hi Vishali,
sessionDestroyed() is called before invalidating the session.
wrox says you can save the data to database or any other cleanups before the session is being invalidated in sessionDestroyed() method.
Well in the same way you can do any session initializations required for your session in sessionCreated() method.
good luck and happy new year,
Ramdhan Yadav K


Ram Dhan Yadav (SCJP, SCWCD, SCJA-I, IBM EC(483))
"We are what we repeatedly do. Excellence, then, is not an act, but a habit."
Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
Originally posted by Ramdhan Kotamaraja:

sessionDestroyed() is called before invalidating the session.


Well, you should refer to the API.


wrox says you can save the data to database or any other cleanups before the session is being invalidated in sessionDestroyed() method.

I would wish so. But wrox is wrong. You cannot do this. I have tried this on Tomcat40 as well.
jyothi ve
Ranch Hand

Joined: Aug 03, 2001
Posts: 51
Try wrox example with HttpSessionListener.
Session Destroyed method getting called when Session timed out. Just now I tried this, its working for me with Tomcat 4.0. Even after closing the browser, you have to wait until timeout period to be over to see the Session Destroyed method get called.
Set the session timeout to 1 min in web.xml to see the results faster

[This message has been edited by jyothi ve (edited December 31, 2001).]


Jyothi<br /> <br />Sun Certified Business Component Developer<br />Sun Certified Web Component Developer<br />Sun Certified Java Programmer<br />Oracle Certified SQL & PL-SQL Programmer
Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
In your sessionDestroyed() method try retrieving any attribute from the session. I get an IllegalStateException. This the means the method is called AFTER the session is destroyed. This is what I am talking about.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

>>This the means the method is called AFTER >>the session is destroyed. This is what I >>am talking about.
Exactly ture. However the purpose of these methods are not to access any part of the session, because you will get an IllegalStateException. The purpose is to close resources like connections, which are usually created in the sessionCreated() method.
Kind of like the finally in a try/catch/finally or better yet as in finalize method of Object.
In reading the API, it says it is a way to "notify" that the session is to be created, or has just been destroyed. I can see a lot of use for this. Some of the use is on the server, which can pool Servlets, and also Sessions.
Hope that clears some things up, and that I didn't get something wrong there.
Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
I cannot see why would you create a database connection in say MyHttpSessionListener class. Even if you do, how will you use that connection? You won't even have a reference to the object of this class.
The only handles you have are the sessionCreated() or sessionDestroyed() methods. For all you know, these method may not even be called if nobody accesses the web application !!!

Some of the use is on the server, which can pool Servlets, and also Sessions.

Could you please be more clear about this? Any example would be helpful.
jyothi ve
Ranch Hand

Joined: Aug 03, 2001
Posts: 51
I hope the use of HttpSessionListener class is to initilize or track information before serving the requests.
For example: For Admin purpose to findout number of active sessions in the given point of time, how many users accessed the site etc.
when session destroy called number of active users will get reduced.
If you want to initialize some session specific information you can do in this method
[This message has been edited by jyothi ve (edited December 31, 2001).]
Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
Originally posted by jyothi ve:
I hope the use of HttpSessionListener class is to initilize or track information before serving the requests.
For example: For Admin purpose to findout number of active sessions in the given point of time, how many users accessed the site etc.
when session destroy called number of active users will get reduced.
If you want to initialize some session specific information you can do in this method

That's what I am trying to say. It seems to be the purpose of this interface but you cannot do any of things that you have mentioned. Can you please write some code to show how will you do this?
All you can do is add some generic attribute (I mean, not even user specific because at this time, you won't know whose session is this) in the sessions as soon as they are created using the sessionCreated() method. Yes, you may get value for this attribute from the database.
But I am unable to think of any other use of this interface. Specifically, I more frustrated by the presence of the "good for nothing" sessionDestroyed() method.
jyothi ve
Ranch Hand

Joined: Aug 03, 2001
Posts: 51
Hi Vaishali Joshi,
Below code tells the uses what I mentioned previously i.e tracking active sessions, number of visitors for this site
********* Java Class implenets Listener *****
package test;
import java.util.Date;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class CounterListenerExample implements HttpSessionListener {
private static int counter = 0;
private static int activeCount = 0;

public void sessionCreated(HttpSessionEvent evt) {
long time = evt.getSession().getCreationTime();
System.out.println("A new session was crated at " + new Date(time));
counter++;
activeCount++;
}
public void sessionDestroyed(HttpSessionEvent evt) {
activeCount--;
System.out.println("A session was destroyed at ");
}
public static String getCounterInfo() {
return "Number of active sessions on server = " + activeCount + "\n" + "No of total visitors to date = " + counter;
}
}
*********************************************
************ JSP which uses above class *****
<%@ page import="test.CounterListenerExample" %>
<html>
<head><title> Example session counter </title></head>
<body bgcolor="#ffffcc">
<h3 align="center"> Counter Example : <h3>
<br>
<%= CounterListenerExample.getCounterInfo() %>
</body>
</html>
*********************************************
Let me know whether I am able to fulfill what I mentioned previously or not
[This message has been edited by jyothi ve (edited December 31, 2001).]
Vaishali Joshi
Greenhorn

Joined: Dec 28, 2001
Posts: 21
Thanks, Jyothi! I get it now.
James Thomas
Greenhorn

Joined: Mar 08, 2004
Posts: 3
I am considering great possibilities with this interface. Specific values added to the session can trigger a tracking process that amounts to an automatic asynchronous notification. Has anyone done this?
Anoop Keni
Greenhorn

Joined: Jul 29, 2004
Posts: 3
Hi,

I used the similar code and mapped it in web.xml in the listener tag. When a new call is made to the jsp page the session is created and incremented in the method sessionCreated(HttpSessionEvent se). but when i close the browser the destroy method is not called.

Any idea how the listener can call sessionDestroyed(HttpSessionEvent se) method? Here i am decrementing the count.

When i retrieve the the count value ... it is only incremented value.

Heres the code for AppSessionCouner

--------------------------------------------------------------------
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;


public class AppSessionCouner implements HttpSessionListener
{

private static int activeSessions = 0;

// Create a new session.
public void sessionCreated(HttpSessionEvent se){
System.out.println("Inside sessionCreated");
System.out.println("Before New session createb = " + activeSessions);
activeSessions++;
System.out.println("After New session count = " + activeSessions);
}

// Destroy the session
public void sessionDestroyed(HttpSessionEvent se){
System.out.println("Inside sessionDestroyed");
if (activeSessions > 0)
{
System.out.println("Count before destroyed = " + activeSessions);
activeSessions--;
System.out.println("Count after destroyed = " + activeSessions);
}

}

// get the count of active session.
public static int getActiveSessions(){
return activeSessions;
}

}

------------------------------------------------------------------

Heres the code i added into web.xml

<!-- Listeners -->
<listener>
<listener-class>
com.camo.po.servlets.AppSessionCouner
</listener-class>
</listener>

-------------------------------------------------------------------


Heres the code I used to check the count on the jsp


<%=AppSessionCouner.getActiveSessions()%>


Thanx.
Hoping for a quick reply.
Phani Kumar Sripada
Greenhorn

Joined: Aug 14, 2003
Posts: 5
Hi Anoop,

Try setting the session time out period in the DD.

Add the below lines to your web.xml. It makes the session to get destroyed one minute after it is created.

<session-config>
<session-timeout>1</session-timeout>
</session-config>

Hope this helps!

Regards,
Phani.

[ July 30, 2004: Message edited by: Phani Kumar Sripada ]
[ July 30, 2004: Message edited by: Phani Kumar Sripada ]

SCJP 1.4
Lakshmi Anantharaman
Ranch Hand

Joined: Aug 01, 2001
Posts: 58
Along these lines . How to capture the browser window closing with Java ?

Resposes appreciated
[ March 29, 2005: Message edited by: Laksh Anan ]
ritesh hk
Greenhorn

Joined: Mar 15, 2005
Posts: 6
firstly, I think the session listener will be more useful for initializing and destroying session attributes such as DB Connections. Session Attributes can be any Object. so you can create DBConnection, and store it as a session attrbute when the session is created. and close these connecteion when the session is destoryed!


and for the Window closing.. u gotta use javascript. window.close() or something like that. you could make this javascript method call a servelt which could do some processing for you (such as: send the user an email that he/she should perform a graceful logout by hitting the logout button )


hth

-ritesh


-------------<br />SCJP 1.4 <br />SCWCD (just started)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: HttpSessionListener: What were they thinking?
 
Similar Threads
doubts in session
How to invalidate a user session, when I only have a session ID?
problem using getSession(boolean create)
Connection Busy with another result hstmt Error - updated (SOLVED WITH JTDS)
doubts on session creation