javax.servlet.http.HttpSessionListener :-


HttpSessionListener interface gets notified each time a session has created or destroyed. You can use it to know when a session is created or destroyed.
It has following methods -

1- sessionCreated() - This method invokes when a session has been created. It has the following syntax -
void sessionCreated(HttpSessionEvent event)        

2- sessionDestroyed() - This method invokes just before a session is being destroy or invalidate. -
public void sessionDestroyed(HttpSessionEvent event)        


HttpSessionEvent -

javax.servlet.http.HttpSessionEvent is an event class corresponding to HttpSessionListener. It sends notification whenever any new session is created or destroyed.
It has the following methods -

1- getSession() - It returns the session object. It has the following syntax -
public HttpSession getSession()        


Example -

This example will count live users and total users visited your website using HttpSessionListener.

1 - index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>HttpSessionListener Demo</title>
    </head>
    <body>
        <form method="get" action="Info">
            <table border="1px">
                <tr>
                    <td>Enter Your User Name </td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td><input type="reset" value="Reset"></td>
                    <td><input type="submit" value="Show total and live users"></td>
                </tr>
            </table>
        </form>
    </body>
</html>    

2- Create a package named listeners and within that create a class named MyListener_1 that will work as a HttpSession Listener -
MyListener_1 - This class implements HttpSessionListener and will increment live_users and total_users variables each time a new session is created. And decrement live_users variable when a session destroyed.


package listeners;

import javax.servlet.http.*;
import javax.servlet.*;

public class MyListener_1 implements HttpSessionListener {

 
    private static int live_users = 0;
    private static int total_users = 0;
    private ServletContext application = null;
    
    public void sessionCreated(HttpSessionEvent event) 
    {
       application = event.getSession().getServletContext();
       
       live_users++;
       total_users++;
      
       application.setAttribute("Live_Users", live_users);
       application.setAttribute("Total_Users", total_users);
    /*application variable remains comman for all the users and can be accessed evrywhere.
      thats why we have stored live_users and total_users within application varaiable. */
    }

    public void sessionDestroyed(HttpSessionEvent se) 
    {
       live_users--;
       application.setAttribute("Live_Users", live_users);
    }
}


3- Create a package named serv and within that create the following servlets -
Info Servlet - This servlet will create a session and set its expiry time to 1 hour. It will also display the information of live users and total users visited your website.

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Info extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            String name = request.getParameter("t1");
            ServletContext application = getServletConfig().getServletContext();
            HttpSession session = request.getSession();
            session.setAttribute("Name", name);
            session.setMaxInactiveInterval(60*60);  //session will expire after 1 hour
            
            out.println("<h1 style='text-align:center; padding:20px'>Welcome</h1>");
            out.println("<hr>");
            out.println("<a href = 'Logout'>Logout</a>");
            out.println("<hr>");
            out.println("<h2>Hi "+name+"</h2>");
            out.println("<b> You are the visiter number - "+ application.getAttribute("Total_Users").toString() +"</b>");
            out.println("<br>");
            out.println("<b> Total Users Onine - "+ application.getAttribute("Live_Users").toString() +"</b>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}


Logout Servlet - By default session will expire in 1 hour as given in Info servlet. Logout servlet will be used to terminate the session any time by user.
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Logout extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession();    
            session.invalidate();
            out.println("You are successfully logout");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}        

4- web.xml - Add the information of servlet's and listener in web.xml file -
<web-app>
    <listener>
        <listener-class>listeners.MyListener_1</listener-class>
    </listener>
    <servlet>
        <servlet-name>Info</servlet-name>
        <servlet-class>servs.Info</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>servs.Logout</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Info</servlet-name>
        <url-pattern>/Info</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>
</web-app>
        


5- Now run the project, It will show you index.html page (copy the url shown in web browser url box), enter User Name and press 'Show total and live users' button -



It will show you total and live users information -



Now open some other web browser (Firefox in our case) and paste the copied url and press enter key. Enter some other user name and press 'Show total and live users' button. It will show you that live users and total users incremented to 2.



Now from any web browser press logout link and refresh the other web browser and you will find that live users will be decremented to one.