For the purpose of learning the packaging of a Java EE 6 application, we will show how to combine some JSF components, such as Managed Beans and JSF views, with some Enterprise components, such as the EJB singleton, which we formerly introduced in Chapter 3, Configuring Enterprise Services.
In this example, we will create a simple caching system that uses an EJB singleton to handle the cache in memory. Later, we will show how to introduce data persistence to keep our cache on a storage.
Let’s start by adding a page named
home.xhtml to your Dynamic Web Project:
This page references a Managed Bean named “manager “, which is used to store and retrieve key/value pairs. Managed Beans are simple Java classes, which are used as models for UI components. In JSF 1.2, for a bean to become a managed bean, you had to register it in the JSF configuration file (faces-config.xml). One of the biggest annoyances was that as the number of beans grew, the JSF configuration file grew as well, and it was difficult to keep track of all names and changes in three different files that were all “connected” (JSF configuration file, the JSF view, and the bean itself).
Luckily, JSF 2 has introduced annotations to register Managed Beans. With annotations, the bean and its registration are in the same place (Java class), so it becomes much easier to manage.
Now, let’s see how to code the PropertyManager Managed Bean:
The most relevant part of this class is the @ManagedBean annotation that registers this class as a JSF Managed Bean. Next, the @EJB annotation that is used to inject the SingletonBean into the class.
The SingletonBean is an EJB, which is marked with the special @javax.ejb.Singleton annotation. A class with such annotation is guaranteed to be instantiated only once, thus it is the middleware equivalent of the J2SE singleton pattern. In the Java EE context, they are primarily used to store application-wide shared data.
Create a new class named SingletonBean. The aim of this class will be to store key-value pairs in HashMap:
This class is intentionally placed in a package com.packtpub.chapter4.entity, since in the next section of this chapter, we will use this class as an Entity for storing data.
If you have completed all these steps correctly, you will end up with a project containing the following items:
By default, a Web application inherits the Web context name from the archive name, which is deployed on the application server. So, in our example, if we deploy an archive named as7project.war, it will be accessible using the Web context name as7project, as shown by the following image:
The context name is, however, customizable, and the simplest way to achieve it (without changing the archive name) is by adding a
jboss-web.xml file to the WEB-INF folder of your project:
The content of this file will include the custom Web context, as specified by the context-root element:
Free Demo for Corporate & Online Trainings.