Home  >  JSP & Servlet

HttpSessionListener Example

By Arvind Rai, July 13, 2018
On this page we will provide HttpSessionListener example. HttpSessionListener is an interface that receives notification events about HttpSession lifecycle changes. HttpSessionListener provides sessionCreated() and sessionDestroyed() method. sessionCreated() executes just after a session is created. sessionDestroyed() executes just before session is invalidated. The sample use of HttpSessionListener is tracking sessions created and destroyed. To use HttpSessionListener we need to create its implementation listener class and that class will either be annotated with @WebListener or configured in web.xml using <listener> tag. @WebListener annotation is supported by Servlet 3.0 +. Here on this page we will create a listener to get total active sessions at any time.


Technologies Used

Find the technologies being used in our example.
1. Java 9
2. Servlet 4.0.1
3. Tomcat 9.0.10
4. Gradle 4.3.1
5. Eclipse Oxygen

Create Listener using HttpSessionListener

HttpSessionListener is used to receive notification events about HttpSession lifecycle changes. It has following methods.
sessionCreated(HttpSessionEvent se): This method executes just after a session is created. A session is created by calling getSession() method of HttpServletRequest instance.

sessionDestroyed(HttpSessionEvent se): This method executes just before a session is invalidated. A session is invalidated by calling invalidate() method of HttpSession instance.

Find the implementation class of HttpSessionListener that will update active session count in ServletContext.
SessionCountListener.java
@WebListener
public class SessionCountListener implements HttpSessionListener {
	private final AtomicInteger sessionCount = new AtomicInteger();
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessionCount.incrementAndGet();
		setActiveSessionCount(se);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		sessionCount.decrementAndGet();
		setActiveSessionCount(se);
	}
	private void setActiveSessionCount(HttpSessionEvent se) {
		se.getSession().getServletContext()
		   .setAttribute("activeSessions", sessionCount.get());
		System.out.println("Total Active Session: " + sessionCount.get());
	}
} 
When a session is created, the active session count is incremented and updated in ServletContext and when a session is invalidated, the active session count is decremented and updated in ServletContext. We can fetch active session count in JSP or Servlet from ServletContext anywhere in our application.
Configure listener using @WebListener:
We annotate our listener with @WebListener to configure.
@WebListener
public class SessionCountListener implements HttpSessionListener {
  ------
} 
Configure listener using web.xml:
To configure listener with web.xml, find the code snippet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
   http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
  
    ------
    <listener>
        <listener-class>com.concretepage.SessionCountListener</listener-class>
    </listener>
</web-app> 

Complete Example

We will create a demo application to count active sessions. When a user will login successfully, we will display current user and total active sessions. We will log in console that when a user is logged in, active session count is incremented and when user is logged out, active session count is decremented. Now find the complete code.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'servlet-demo'
version = '0.0.1-SNAPSHOT' 
sourceCompatibility = 9

repositories {
    mavenCentral()
}
dependencies {
    compile 'javax.servlet:javax.servlet-api:4.0.1'
} 
SessionCountListener.java
package com.concretepage;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionCountListener implements HttpSessionListener {
	private final AtomicInteger sessionCount = new AtomicInteger();
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessionCount.incrementAndGet();
		setActiveSessionCount(se);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		sessionCount.decrementAndGet();
		setActiveSessionCount(se);
	}
	private void setActiveSessionCount(HttpSessionEvent se) {
		se.getSession().getServletContext()
		   .setAttribute("activeSessions", sessionCount.get());
		System.out.println("Total Active Session: " + sessionCount.get());
	}
} 
LoginServlet.java
package com.concretepage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = "/loginAction", loadOnStartup = 1)
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
	     doGet(request, response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	     response.setContentType("text/html");
	     String userName = request.getParameter("username");
	     String passowrd = request.getParameter("password");
	     
	     PrintWriter out = response.getWriter();
	     if (!userName.isEmpty() && userName.equalsIgnoreCase(passowrd)) {
	    	 //login success
	    	 HttpSession session = request.getSession();
	    	 session.setAttribute("username", userName);
		 out.println("<h3>Login Success</h3>");	    	 
		 out.println("Total Active Session: "+ request.getServletContext().getAttribute("activeSessions"));
		 out.println("<br/>Current User: "+ session.getAttribute("username"));
		 out.println("<form name=\"logoutForm\" method=\"POST\" action=\"logoutAction\">");
		 out.println("<br/><input type=\"submit\" value=\"Logout\"/>");
		 out.println("</form>");
	     } else {
	    	 //login failed
		 out.println("Login Failed.");
	     }
	}
} 
LogoutServlet.java
package com.concretepage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = "/logoutAction", loadOnStartup = 1)
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
	     response.setContentType("text/html");
	     HttpSession session = request.getSession();
	     session.invalidate();
	     PrintWriter out = response.getWriter();
	     out.println("<h3>Successfully Logged Out.</h3>");
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	     doPost(request, response);
	}
} 
index.html
 <html>
  <head><title>User Login</title></head>
  <body>
        <h2>User Login</h2>
        <form name="loginForm" method="POST" action="loginAction">
            <p>Username: <input type="text" name="username"/></p>
            <p>Password: <input type="password" name="password"/></p>
            <p> <input type="submit" value="Login"/></p>
        </form>       
   </body>
</html> 

Test Application

Download the demo project source code. Go to the root folder of the project using command prompt and run the command.
gradle clean build 
A WAR file will be created in build/libs directory. Deploy the WAR file in tomcat and access the URL as given below.
http://localhost:8080/servlet-demo/ 
Access the URL from more than one browser and login. Enter any word as username and same word as password to login successfully. Suppose we have logged in successfully from three browsers. The third user will get message as following.
HttpSessionListener Example
When the user is logged out, total active session will be decremented. We can see those messages in console log.

Reference

Interface HttpSessionListener

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us