Step 3: Add a Context Listener Class

The Guest entity objects will be stored in an ObjectDB database, which will be represented by a JPA's EntityManagerFactoryjavax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.See JavaDoc Reference Page... instance with a global application scope.

We have to register a ServletContextListener to perform initialization and cleanup operations:

  • The database will be opened (or created if not existing yet) when the web application starts, by instantiating an EntityManagerFactory.
  • The database will be closed when the web application stops (or when the web server shuts down), by closing the EntityManagerFactory.

To register a ServletContextListener:

  • Open the [New Listener] dialog box by right clicking the guest package node (in the [Package Explorer] window), selecting New > Other... > Web > Listener and clicking Next.
  • The Java package name should be guest.
  • Enter GuestListener as the class name - use exactly that case sensitive class name.
  • Click Next and then Select All to enable the Finish button.
  • Click Finish to create the new listener class.

Now replace the content of the new source file with the following code:

package guest;
import javax.persistence.*;
import javax.servlet.*;
public class GuestListener implements ServletContextListener {

    // Prepare the EntityManagerFactory & Enhance:
    public void contextInitialized(ServletContextEvent e) {
        EntityManagerFactory emf =
        e.getServletContext().setAttribute("emf", emf);
    // Release the EntityManagerFactory:
    public void contextDestroyed(ServletContextEvent e) {
        EntityManagerFactory emf =

The code above:

  • Invokes the Enhancer to enhance the entity class, creates an EntityManagerFactory instance and stores it as an application scope attribute in the servlet context - when the web application starts (contextInitialized).
  • Retrieves the EntityManagerFactory from the application scope attribute and closes the EntityManagerFactory and the database - when the application stops (contextDestroyed).

The next step is adding a servlet class that will manage the guestbook page.