Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Singleton Session Bean by name "ActiveFollowersOnline.java". A Singleton Session Bean is a enterprise bean which are instantiated once per application and has lifecycle till application is alive.
Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:
Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Session Bean as shown in fig below.
Step 3: Click
.
New Session Bean dialog box gets open. It prompts us to enter EJB Name: , Project: , Location: , Package: , Session Type: and Create Interface: etc. Enter the values as shown in the fig below.
package com.hubberspot.ejb; import javax.ejb.Singleton; import javax.ejb.LocalBean; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; // @Singleton annotation informs container that // treat this bean as a Singleton bean. // @LocalBean annotation informs container that // this session bean exposes a no-interface view. // @WebListener annotation informs container that // this class is a web listener which will listen to // various events happening during lifecyle of application // Here this class listens to Http Session when a session // is created or destroyed. // We make class implements HttpSessionListener which has two // methods sessionCreated() and sessionDestroyed() , which // are called by the container whenever a session is created // or destroyed @Singleton @LocalBean @WebListener public class ActiveFollowersOnline implements HttpSessionListener { private static int followersOnline = 0; @Override public void sessionCreated(HttpSessionEvent se) { System.out.print("Session Created : "); followersOnline++; } @Override public void sessionDestroyed(HttpSessionEvent se) { followersOnline--; } public int getFollowersOnline() { return followersOnline; } }
In the next section of this blog (part 8) you will learn how to create a Servlet in NetBeans for this application in the Web module.