Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

Session Listener Filter

$
0
0

A simple session listener can help to understand the beginning and closing of Http session. All we have to do is to implement the HttpSessionListner interface. The interface provides basic methods like sessionCreated and sessionDestroyed. In the implementation of these method we can add logic to capture and log the details of session.

Snippet

  1. packagewlsunleashed.servlets;
  2.  
  3. importjavax.servlet.http.HttpSession;
  4. importjavax.servlet.http.HttpSessionEvent;
  5. importjavax.servlet.http.HttpSessionListener;
  6.  
  7. /*
  8. *  Simple Session Listener for maintaining the user's footprints
  9. */
  10.  
  11. publicclass SimpleSessionListener implements HttpSessionListener {
  12.  
  13.         HttpSession session =null;
  14.  
  15.         // default constructor
  16.         public SimpleSessionListener(){
  17.         }
  18.  
  19.         // Life cycle event invoked when the session is created
  20.         // Adds a counter to the session to tract the user's visit to the site
  21.         publicvoid sessionCreated(HttpSessionEvent evt){
  22.                 session = evt.getSession();
  23.                 Long visitCount =newLong(1);
  24.                 System.out.println("Session Created");
  25.                 session.setAttribute("visit_Count", visitCount);
  26.         }
  27.  
  28.         // Life cycle event invoked when the session is destroyed
  29.         // Prints the total number of visits to the server by the server
  30.         publicvoid sessionDestroyed(HttpSessionEvent evt){
  31.                 session = evt.getSession();
  32.                 System.out.println("Session Destroyed");
  33.                 Long visitCount =(Long) session.getAttribute("visit_Count");
  34.                 if(visitCount ==null)
  35.                         visitCount =newLong(1);
  36.                 else
  37.                         visitCount =newLong(visitCount.longValue()+1);
  38.                 System.out.println("Total Number of Hits="+ visitCount.longValue());
  39.  
  40.         }
  41. }

Viewing all articles
Browse latest Browse all 178

Trending Articles