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 EntityManagerFactory
javax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. 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 File] dialog box by right clicking the guest package node (in the [Projects] window) and selecting New > Other...
- Select Web > Web Application Listener and click Next.
- Enter GuestListener as the class name - use exactly that case sensitive class name.
- The Java package name should be guest.
- 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.*; @WebListener public class GuestListener implements ServletContextListener { // Prepare the EntityManagerFactory & Enhance: public void contextInitialized(ServletContextEvent e) { com.objectdb.Enhancer.enhance("guest.*"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("$objectdb/db/guest.odb"); e.getServletContext().setAttribute("emf", emf); } // Release the EntityManagerFactory: public void contextDestroyed(ServletContextEvent e) { EntityManagerFactory emf = (EntityManagerFactory)e.getServletContext().getAttribute("emf"); emf.close(); } }
The code above:
- Invokes the Enhancer to enhance the entity class and 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 theEntityManagerFactory
and the database - when the application stops (contextDestroyed
).
The next step is adding a servlet class that will manage the guestbook page.