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
- packagewlsunleashed.servlets;
- importjavax.servlet.http.HttpSession;
- importjavax.servlet.http.HttpSessionEvent;
- importjavax.servlet.http.HttpSessionListener;
- /*
- * Simple Session Listener for maintaining the user's footprints
- */
- publicclass SimpleSessionListener implements HttpSessionListener {
- HttpSession session =null;
- // default constructor
- public SimpleSessionListener(){
- }
- // Life cycle event invoked when the session is created
- // Adds a counter to the session to tract the user's visit to the site
- publicvoid sessionCreated(HttpSessionEvent evt){
- session = evt.getSession();
- Long visitCount =newLong(1);
- System.out.println("Session Created");
- session.setAttribute("visit_Count", visitCount);
- }
- // Life cycle event invoked when the session is destroyed
- // Prints the total number of visits to the server by the server
- publicvoid sessionDestroyed(HttpSessionEvent evt){
- session = evt.getSession();
- System.out.println("Session Destroyed");
- Long visitCount =(Long) session.getAttribute("visit_Count");
- if(visitCount ==null)
- visitCount =newLong(1);
- else
- visitCount =newLong(visitCount.longValue()+1);
- System.out.println("Total Number of Hits="+ visitCount.longValue());
- }
- }