HttpSessionListener  problem

i implemented a class with HttpSessionListener to capture the Session Creation and destruction events.
In my session creation event i created an attribute as follows
Class A implements HttpSessionListener
sessionCreated(event)
     B b = new B();
     event.getSession().setAttribute("b", b);
     From above we can infer that whenever Session is being created the above sessionCreated method
     will be called.(i.e) the session should definetly contain attribute "b"
so what is the problem?
There are times where the below statement is
request.getSession().getAttribute("b"); returning null (Because of the above it should always return
a valid value but it is returning null)
The problem is not happening on a regular basis but it is happening occasionally.
Iam wondering what sequence of actions has made the above statement to return null.
Any clue on where it might have gone wrong.
Edited by: rama.krishna on Dec 7, 2007 9:17 AM

I understood the problem that iam facing.Thanks
is being explained at http://developerinsight.wordpress.com/category/core-java/httpsession/

Similar Messages

  • Problem with HttpSessionListener

    I'm getting error with the following code...Can anybody help me in this?
    import java.util.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.*;
    import javax.servlet.http.HttpSessionEvent;
    import java.sql.* ;
    public class SessionTimeoutNotifier implements HttpSessionListener,HttpSessionBindingListener
    public void valueBound(HttpSessionBindingEvent event)
    System.out.println("The session has started : "+event.getSession().getId());
    public void sessionCreated(HttpSessionEvent se)
    System.out.println( "Session with id " + se.getSession().getId() + " created!" ) ;
    public void sessionDestroyed(HttpSessionEvent se)
    System.out.println( "Session with id " + se.getSession().getId() + " destroyed!" ) ;
    Error is
    /SessionTimeoutNotifier.java:8: cannot resolve symbol
    [javac] symbol : class HttpSessionEvent
    [javac] location: package http
    [javac] import javax.servlet.http.HttpSessionEvent;
    [javac] ^
    SessionTimeoutNotifier.java:11: cannot resolve symbol
    [javac] symbol : class HttpSessionListener
    [javac] location: class com.equifax.apply.usaa.SessionTimeoutNotifier
    [javac] public class SessionTimeoutNotifier implements HttpSessionListener,HttpSessionBindingListener
    [javac] ^
    SessionTimeoutNotifier.java:28: cannot resolve symbol
    [javac] symbol : class HttpSessionEvent
    [javac] location: class com.equifax.apply.usaa.SessionTimeoutNotifier
    [javac] public void sessionCreated(HttpSessionEvent se)
    [javac] ^
    SessionTimeoutNotifier.java:33: cannot resolve symbol
    [javac] symbol : class HttpSessionEvent
    [javac] location: class com.equifax.apply.usaa.SessionTimeoutNotifier
    [javac] public void sessionDestroyed(HttpSes
    I'm using jdk1.3 ..

    There is no problem with class pathIt's telling you it can't find that class. Do you think the compiler is lying to you?
    n I found HttpSessionListener class in jdk1.3 specYes, but have you seen the class file in the classpath?
    it is strange, but the error message is still rather clear IMO.

  • Problem adding HttpSessionListener

    Hi,
       I'm trying to implement HttpSessionListener for user logout. When ever I click on the package and select Listener it adds properly into Listener Candidates tree but doesn't add any entry into web.xml.
       I have tried right-clicking on the listener under candidates tree and selected the option 'Add to web.xml'; This time the entry is added into web.xml, but shows an error (shows a red mark in tree and doesn't allow me build the project) in web.xml.

    Hi Chaitinya,
    You have to perform two basic tasks so that your event listener is ready to handle events. These are:
    1. Develop an event listener class that implements the appropriate listener interface.
    2. You must declare the listener class in the deployment descriptor of your Web application.
    Also check on to this link for guidance.
    <a href="http://help.sap.com/saphelp_erp2005/helpdata/en/80/8bc5607c4ee54a8c2c61a91b3689d9/frameset.htm">HttpSessionListener</a>
    Hope it helps,
    Regards,
    Nagarajan.

  • Problem with beans in session scope

    Hello,
    I developped a website using JSP/Tomcat and I can't figure out how to fix this problem.
    I am using beans in session scope to know when a user is actualy logged in or not and to make some basic informations about him avaible to the pages. I then add those beans to an application scope bean that manages the users, letting me know how many are logged in, etc... I store the user beans in a Vector list.
    The problem is that the session beans never seem to be destroyed. I made a logout page which use <jsp:remove/> but all it does is to remove the bean from the scope and not actualy destroying it. I have to notify the application bean that the session is terminated so I manualy remove it from its vector list.
    But when a user just leave the site without using the logout option, it becomes a problem. Is there a way to actualy tell when a session bean is being destroyed ? I tried to check with my application bean if there are null beans in the list but it never happens, the user bean always stays in memory.
    Is there actualy a way for me to notify the application bean when the user quits the website without using the logout link ? Or is the whole design flawed ?
    Thanks in advance.
    Nicolas Jaccard

    I understand I could create a listener even with my current setup Correct, you configure listeners in web.xml and they are applicable to a whole web application irrespective of whether you use jsp or servlets or both. SessionListeners would fire when a session was created or when a session is about to be dropped.
    but I do not know how I could get a reference of the application bean in >question. Any hint ?From your earlier post, I understand that you add a UserBean to a session and then the UserBean to a vector stoed in application scope.
    Something like below,
    UserBean user = new UserBean();
    //set  bean in session scope.
    session.setAttribute("user", user);
    //add bean to a Vector stored in application scope.
    Vector v = (Vector)(getServletContext().getAttribute("userList"));
    v.add(user);If you have done it in the above fashion, you realize, dont you, that its the same object that's added to both the session and to the vector stored in application scope.
    So in your sessionDestroyed() method of your HttpSessionListener implementation,
    void sessionDestroyed(HttpSessionEvent event){
         //get a handle to the session
         HttpSession session = event.getSession();
          //get a handle to the user object
          UserBean user = (UserBean)session.getAttribute("user");
           //get a handle to the application object
          ServletContext ctx = session.getServletContext();
           //get a handle to the Vector storing the user objs in application scope
            Vector v = (Vector)ctx.getAttribute("userList");
           //now remove the object from the Vector passing in the reference to the object retrieved from the Session.
            v.removeElement(user);
    }That's it.
    Another approach would be to remove the User based on a unique identifier. Let's assume each User has a unique id (If your User has no such feature, you could still add one and set the user id to the session id that the user is associated with)
    void sessionDestroyed(HttpSessionEvent event){
         //get a handle to the session
         HttpSession session = event.getSession();
          //get a handle to the user object
          UserBean user = (UserBean)session.getAttribute("user");
           //get the unique id of the user object
           String id = user.getId();
           //get a handle to the application object
          ServletContext ctx = session.getServletContext();
           //get a handle to the Vector storing the user objs in application scope
            Vector v = (Vector)ctx.getAttribute("userList");
           //now iterate all user objects in the Vector
           for(Iterator itr = v.iterator(); itr.hasNext()) {
                   User user = (User)itr.next();               
                    if(user.getId().equals(id)) {
                           //if user's id is same as id of user retrieved from session
                           //remove the object
                           itr.remove();
    }Hope that helps,
    ram.

  • What's wrong about HttpSessionListener?

    I' ve 2 Listerners;
    the first one ContextListener it's work.
    but SessionListenerCounter doesn't.
    What 's wrong?
    Compilation successfully but Runtime it 's show SEVERE: Error listenerStart.
    Please,
    thank you.
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class SessionListenerCounter implements HttpSessionListener
        public SessionListenerCounter()
        public void sessionCreated(HttpSessionEvent se)
            System.out.println("Session Created");
        public void sessionDestroyed(HttpSessionEvent se)
              System.out.println("Session Destroyed");
    }

    I dont know if it actually helps, but following the link
    http://www.cs.pub.ro/~gaburici/nstomcat/diss.html#solpre
    there are some problems mentioned that still seem to be in Java for Linux/Unix.
    Try to set
    LD_PRELOAD=/usr/j2sdk1.4.2/jre/lib/sparc/client/libjvm.so
    before you start the program.
    (I assume you loaded the library via dlopen)
    Hope it works...

  • Get Request in HttpSessionListener ??

    Hi,
    I would like to create a HttpSessionListener which assigns some default attributes based upon values which are available in the http request (base url, query parameters etc).
    The problem is that it is not possible to get the request in the HttpSessionListener. Does someone know an alternative to set up the session in a way that I can get the values in the request. I created a Filter to do this but it's not that nice? Is there a better way??
    I would like to get the request in the HttpSessionListener, shame I can't get it.
    Cheers,
    Steve

    You can't that way... Even though session objects are created when requests are made for which there is no valid existing session, the session is not itself associated with requests. The association is only in one direction.
    The best you can do is to, in the request page that you need this data, check if it's in the session already and if not, add it, that way you init it only when needed.

  • Problem with jdk

    hi,
    im using j2sdk 1.4.2 with realJ as my IDE. the problem is that when i try to compile servlet codes with realJ, it shows errors when I import the servlet classes. eg:
    C:\Documents and Settings\kovenant\Desktop\servlet.java:2: package javax.servlet.http does not exist
    import javax.servlet.http.*;
    ^
    any idea wats the problem?? thanx in advance

    Hi, I'm having the same package javax.servlet.http does not exist error. I've been reading past postings on the forum and tried the methods but none of them works.
    My code as follows:
    package Helpdesk;
    import javax.servlet.http.*;
    public class SessionCount implements HttpSessionListener
         private static int numberOfSessions = 0;
         public void sessionCreated (HttpSessionEvent evt)
              numberOfSessions++;
         public void sessionDestroyed (HttpSessionEvent evt)
              numberOfSessions--;
              return numberOfSessions;
    Error as follows
    C:\Program Files\Apache Group\Tomcat 4.1\webapps\g-megastore\src>javac SessionCount.java
    SessionCount.java:3: package javax.servlet.http does not exist
    import javax.servlet.http.*;
    ^
    SessionCount.java:5: cannot resolve symbol
    symbol : class HttpSessionListener
    location: class Helpdesk.SessionCount
    public class SessionCount implements HttpSessionListener
    ^
    SessionCount.java:9: cannot resolve symbol
    symbol : class HttpSessionEvent
    location: class Helpdesk.SessionCount
    public void sessionCreated (HttpSessionEvent evt)
    ^
    SessionCount.java:14: cannot resolve symbol
    symbol : class HttpSessionEvent
    location: class Helpdesk.SessionCount
    public void sessionDestroyed (HttpSessionEvent evt)
    ^
    SessionCount.java:20: return outside method
    return numberOfSessions;
    ^
    5 errors
    My classpath is set as:
    set classpath=C:\Program Files\Apache Group\Tomcat 4.1\webapps\g-megastore\WEB-INF\classes
    both servlet.jar and j2ee.jar are in this \classes folder.
    What went wrong?

  • How to access HttpSessionListener instance

    Hi,
    I use a HttpSessionListener to count the active sessions in my WebApp. Therefore the HttpSessionListener implementation has two fields (an int and an ArrayList<HttpSession>). The HttpSessionListener is defined in the web.xml.
    The listener works as expected and updates the fields each time a Session is created or destroyed.
    How can I access the fields from within the application? Esp. how can I access the ArrayList field to used that in the application?
    Is the instance of the HttpSessionListener somewhere in the Application context?
    Thanks

    Two ways:
    1) Make the list static. It may only lead to problems in certain clustered environments.
    2) On the first-time use, let it put itself in the application scope.

  • SAPNoClassDefFoundError: javax.servlet.http.HttpSessionListener

    Hi,
    I have deployed an application in to Netweaver WAS, and have given a hard reference to one of the libraries which is already deployed in the same server. But when starting the application, it gives an error telling that <b><i>javax.servlet.http.HttpSessionListener</i></b> is not available. I gave the servlet.jar in the classpath and still its giving the same error.
    Can anyone tell me what can i do to get rid of this problem? This is the error message iam getting in the defaulttrace file:
    <b><i>The error is: com.sap.engine.frame.core.load.SAPNoClassDefFoundError: javax.servlet.http.HttpSessionListener</i></b>

    Hi Venkat
    Check in the visual admin-deploy service,whether or not your application is deployed.Try to start it.
    Also check out the below link
    http://help.sap.com/saphelp_nw2004s/helpdata/en/1b/92e4e701b242c2833a7adde6ecad09/frameset.htm
    Message was edited by:
            Rajat Anand
    Message was edited by:
            Rajat Anand

  • Quesiton about HttpSessionListener in Tomcat 5.0.25

    Hi there
    I have the following class implementing HttpSessionListener:
    package com.mycompany;
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    public class MyListener implements HttpSessionListener
    public void sessionCreated(HttpSessionEvent event)
    HttpSession session = event.getSession();
    System.out.println("Session was created for id="+session.getId());
    public void sessionDestroyed(HttpSessionEvent event)
    HttpSession session = event.getSession();
    System.out.println("Session was destroyed for id="+session.getId());
    The class is deployed in web.xml as:
    <listener>
    <listener-class>com.mycompany.MyListener</listener-class>
    </listener>
    Now, if I start Tomcat and access my application, I can see the message indicating that the session was created. If I keep sending requests, the message does not appear since the session has been created. (so far, so good)
    If I close the browser and open it again to access my application, I can see the message that another session was created. Subsequent requests do not show the message. (so far, so good)
    The problem comes here:
    1. you start tomcat
    2. you open the browser and send the request to the server (you see the message, so the listener is called)
    3. you shut down tomcat
    4. you start tomcat again (previous session is obviously invalid)
    5. you refresh the screen in the browser (the browser sends the cookie with the old session id)
    6. The application generates the response and a new session is created, HOWEVER the message is NOT displayed (meaning that the listener was not called).
    Please note that in all cases a proper session is created/used, but in my test, the listener is not being called if the browser sends a session that is not valid to the server (or at least, that is what it appears....)
    The specification (Servlet2-4, Nov 24th-2003, pg 276) says that sessionCreated is called when a session WAS created. If I have a new HttpSession, I should get a call to the listener... right?
    I am currently using: WindowsXP, jdk 1.4.2_04, Tomcat 5.0.25
    I'm probably doing something wrong but I cannot figure out what it is. Any help/suggestions/comments are appreciated.
    Thanks in advance
    Leo.

    Are you sure that a new session is being created in step 6? Tomcat can be configured to persist sessions between restarts. Maybe check getCreationTime() on the session?
    --Jon                                                                                                                                                                                                                                                                                                                                                               

  • HttpSessionListener must be a bean?

    Hi
    i have some problem to implement the HttpSessionListener Interface to a class. I thought i read somewhere that a class implementing HttpSessionListener Interface must be a bean. Is that right?
    If so, that would mean, that the constructor of that class may not have a parameter, right (i didn't worked with beans untill now)? So if i need a reference to my servlet from the "HttpSessionListener Class" i need to create this reference later using a methode that registers my Servlet somehow?!
    Thanks for your help.

    I have solved a part of the problem. I now can create a class implementing a HttpSessionListener and deploy it in the webapp (web.xml). It's working, means, i see when a session is created and when a session is destroyed (with System.out.println()). The class implementing the HttpSessionListener seems to be initialized before the servlet. So i don't have to create an instance of that class in my servlet.
    The remaining problem is, that i need to get a reference to the class with the listener and that class needs to get a reference to my servlet because the sessionCreated() and SessionDestroyed methode need to call methodes in my Servlet. How can this be done? I think I need to get a reference to the obvisouly already existing instance of the listener class, right? But how is this done?
    Thanks for your help!

  • HttpSessionListener: how to get the username?

    When a session is created, I want to read some data from database
    and store it as session variables. What data is to be read depends
    on the user name.
    I use the HttpSessionListener.
    How can I get the username from within the sessionCreated method?
    I could getRemoteUser() from HttpServletRequest, but how do I get
    the request?
    J2EE API documentation says:
    public interface HttpSession
    Provides a way to identify a user across more than one page request or
    visit to a Web site and to store information about that user.
    Therefore, my problem ought to have a solution, oughtn't it?

    You'd like to think so.
    Unfortunately, the Servlets 2.3 spec does not appear to address combining deployer-based authentication with deployer-based listener classes. This means it's pretty much up to the vendors whether you can do this.
    I'm using jetty/jboss, and the situation is as follows:
    Authentication info is stored in the session only if you use form-based authentication (which, as I found, means you're forced to use form-based authentication if you want your users to be able to log off.)
    However, even if you are using form-based authentication, there are two problems.
    1. your HttpSessionListener implementing class gets called BEFORE they login (i.e. before the login page is presented). So there's nothing in the session yet.
    2. How the container stores the authentication info in the session is entirely up to the vendor. In the case of jetty, the login is stored in the session property "org.mortbay.jetty.Auth".
    So in the case of Jetty, you'd need to implement HttpSessionAttributesListener, wait for that property to be set, and then get the stuff from the db based on that setting. Needless to say, this is highly non-portable. sigh.
    I think the only way to do what we want is to forget HttpServletRequest and use a filter instead. Bummer.
    Did you come up with any bright ideas in the end?

  • HttpSessionListner's sessionCreated() problem

    Hello everyone,
    There is a class implementing HttpSessionListner as follows:-
    public class SessionListnr implements HttpSessionListener{
    public static int i=0;
    public void sessionCreated(HttpSessionEvent arg0) {
              i+=1;
              System.out.println("Session Created: "+i);
         public void sessionDestroyed(HttpSessionEvent arg0) {
              i-=1;
              System.out.println("Session destroyed: "+i);
    And other is JSP where i did this soon after the login validation:-
    SessionListner lis = new Listner();
    session.setAttribute("valid", list);
    My problem is the counter should be '1' after its login and should never increase but unfortunately it increases. I have used same procedure in servlets in order to count for online users but its not working in JSP. Server Technology used is Apache Tomcat. There might be some point i' m missing hope some one amongst you may know it.
    Any help will be appreciated.
    @simer

    Value to 'i' should not be increased as it is not yet published on net. Therefore there aren't any concurrent session.
    And this procedure was working fine with servlets and session management in both is close to similar.
    In my JSP code it is this:-
    SessionListnr lis = new SessionListnr(); // This class implements HttpSessionListner
    session.setAttribute("valid", lis);
    sessionDestroyed() is getting at right time during the call of session.invalidate() method
    but sessionCreated() is getting called during opening webproject login page in browser
    Thanks for reply,
    simer
    Edited by: simer.anand88 on Jul 10, 2010 4:20 AM

  • HttpSessionListener.sessionDestroyed is called after session expired

    Hi
    I implemented HttpSessionListener as I need to save some data from the session when it is timed out.
    The javadoc say:
    " Notification that a session is about to be invalidated. "
    I understand from this that the session is still there when sessionDestoyed() is called
    but running my code suggests that the session already expired at this point.
    Can someone explian if this is how it should be ???
    Thanks

    You're right, sorry. The behaviour has been clarified since. From the Servlet 2.4 specs:
    >
    SRV.1.6.1 HttpSessionListener.sessionDestroyed
    In the previous versions of the specification, this method was defined as:
    Notification that a session was invalidated.
    As of Version 2.4, this method is changed to:
    Notification that a session is about to be invalidated
    so that it notifies before the session invalidation. If the code assumed the previous
    behavior, it must be modified to match the new behavior.
    >
    So what's the problem that you're facing? Do you get the session as null if you try to get it?
    The only reason I can think of is if you declared your web.xml with the spec 2.3 DTD instead of the 2.4. Maybe that makes Tomcat behave according to the old specs. I really don't know if this is the case but you could give this a try.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

Maybe you are looking for