Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Servlets Code Examples

Count total number of live sessions in a web application

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
Count total number of live sessions in a web application --- JSP page for testing (test.jsp) -- <% Integer icount = (Integer)session.getAttribute("count"); out.println("total live sessions "+icount); %> --- Servlet that handles session count -- import javax.servlet.*; import javax.servlet.http.*; public final class CounterListener implements HttpSessionListener { private int count = 1; private ServletContext context = null; public synchronized void sessionCreated(HttpSessionEvent se) { count++; log("sessionCreated("+se.getSession().getId()+") count="+count); se.getSession().setAttribute("count",new Integer(count)); } public synchronized void sessionDestroyed(HttpSessionEvent se) { count--; log("sessionDestroyed("+se.getSession().getId()+") count="+count); se.getSession().setAttribute("count",new Integer(count)); } public int getCount() { return this.count; } public void addCount() { count++; } private void log(String message) { if (context != null) context.log("SessionListener: " + message); else System.out.println("SessionListener: " + message); } }//close class CounterListener --- web.xml file modification -- <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Welcome to Tomcat</display-name> <!-- add this line of code --> <listener> <listener-class>CounterListener</listener-class> </listener> <description> Welcome to Tomcat </description> </web-app>