Subscribe below and get all best seller courses for free .
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.
package com.hubberspot.javaee.listener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener public class OnlineUsersCounter implements HttpSessionListener < private static int numberOfUsersOnline; public OnlineUsersCounter() < numberOfUsersOnline = 0; >public static int getNumberOfUsersOnline() < return numberOfUsersOnline; >public void sessionCreated(HttpSessionEvent event) < System.out.println("Session created by Id : " + event.getSession().getId()); synchronized (this) < numberOfUsersOnline++; >> public void sessionDestroyed(HttpSessionEvent event) < System.out.println("Session destroyed by Id : " + event.getSession().getId()); synchronized (this) < numberOfUsersOnline--; >> >
Running the below servlet on three different browsers will provide output as : (see fig below)
package com.hubberspot.javaee; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; 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; import com.hubberspot.javaee.listener.OnlineUsersCounter; // @WebServlet annotation has a initParams field which takes // in initialization parameters for a servlet. // @WebInitParam annotation takes in a name and value for the // initialization parameters for the current Servlet. @WebServlet(name = "HelloWorldServlet" , urlPatterns = < "/HelloWorldServlet" >, initParams = < @WebInitParam(name = "user" , value = "Jonty") >) public class HelloWorldServlet extends HttpServlet < protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException < response.setContentType("text/html"); PrintWriter out = response.getWriter(); // sessionCreated method gets executed HttpSession session = request.getSession(); session.setMaxInactiveInterval(60); try < out.println(""); out.println(""); out.println("Number of Users Online : " + OnlineUsersCounter.getNumberOfUsersOnline() + "
"); out.println(""); out.println(""); > finally < out.close(); >> >
Output of the program :
1. Eclipse Browser