Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

The encoder Example: Using Alternatives

The Coder Interface and Implementations

The encoder Facelets Page and Managed Bean

Running the encoder Example

To Build, Package, and Deploy the encoder Example Using NetBeans IDE

To Run the encoder Example Using NetBeans IDE

To Build, Package, and Deploy the encoder Example Using Ant

To Run the encoder Example Using Ant

The producermethods Example: Using a Producer Method To Choose a Bean Implementation

Components of the producermethods Example

Running the producermethods Example

To Build, Package, and Deploy the producermethods Example Using NetBeans IDE

To Build, Package, and Deploy the producermethods Example Using Ant

To Run the producermethods Example

The billpayment Example: Using Events and Interceptors

The PaymentEvent Event Class

The PaymentHandler Event Listener

The billpayment Facelets Pages and Managed Bean

The LoggedInterceptor Interceptor Class

Running the billpayment Example

To Build, Package, and Deploy the billpayment Example Using NetBeans IDE

To Build, Package, and Deploy the billpayment Example Using Ant

To Run the billpayment Example

The decorators Example: Decorating a Bean

Components of the decorators Example

Running the decorators Example

To Build, Package, and Deploy the decorators Example Using NetBeans IDE

To Build, Package, and Deploy the decorators Example Using Ant

To Run the decorators Example

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example

Index

 

The producerfields Example: Using Producer Fields to Generate Resources

The producerfields example, which allows you to create a to-do list, shows how to use a producer field to generate objects that can then be managed by the container. This example generates an EntityManager object, but resources such as JDBC connections and datasources can also be generated this way.

The producerfields example is the simplest possible entity example. It also contains a qualifier and a class that generates the entity manager. It also contains a single entity, a stateful session bean, a Facelets page, and a managed bean.

The Producer Field for the producerfields Example

The most important component of the producerfields example is the smallest, the db.UserDatabaseEntityManager class, which isolates the generation of the EntityManager object so it can easily be used by other components in the application. The class uses a producer field to inject an EntityManager annotated with the @UserDatabase qualifier, also defined in the db package:

@Singleton
public class UserDatabaseEntityManager {

    @Produces
    @PersistenceContext
    @UserDatabase
    private EntityManager em;
    ...
}

The class does not explicitly produce a persistence unit field, but the application has a persistence.xml file that specifies a persistence unit. The class is annotated javax.inject.Singleton to specify that the injector should instantiate it only once.

The db.UserDatabaseEntityManager class also contains commented-out code that uses create and close methods to generate and remove the producer field:

 /* @PersistenceContext
    private EntityManager em;

    @Produces
    @UserDatabase
    public EntityManager create() {
        return em;
    } */

    public void close(@Disposes @UserDatabase EntityManager em) {
        em.close();
    }

You can remove the comment indicators from this code and place them around the field declaration to test how the methods work. The behavior of the application is the same with either mechanism.

The advantage of producing the EntityManager in a separate class rather than simply injecting it into an enterprise bean is that the object can easily be reused in a typesafe way. Also, a more complex application can create multiple entity managers using multiple persistence units, and this mechanism isolates this code for easy maintenance, as in the following example:

@Singleton
public class JPAResourceProducer {
    @Produces 
    @PersistenceUnit(unitName="pu3")
    @TestDatabase 
    EntityManagerFactory customerDatabasePersistenceUnit;

    @Produces 
    @PersistenceContext(unitName="pu3")
    @TestDatabase 
    EntityManager customerDatabasePersistenceContext;
    
    @Produces 
    @PersistenceUnit(unitName="pu4")
    @Documents
    EntityManagerFactory customerDatabasePersistenceUnit;

    @Produces 
    @PersistenceContext(unitName="pu4")
    @Documents 
    EntityManager docDatabaseEntityManager;"
}

The EntityManagerFactory declarations also allow applications to use an application-managed entity manager.

The producerfields Entity and Session Bean

The producerfields example contains a simple entity class, entity.ToDo, and a stateful session bean, ejb.RequestBean, that uses it.

The entity class contains three fields: an autogenerated id field, a string specifying the task, and a timestamp. The timestamp field, timeCreated, is annotated with @Temporal, which is required for persistent Date fields.

@Entity
public class ToDo implements Serializable {

    ...
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    protected String taskText;
    @Temporal(TIMESTAMP)
    protected Date timeCreated;

    public ToDo() {
    }

    public ToDo(Long id, String taskText, Date timeCreated) {
        this.id = id;
        this.taskText = taskText;
        this.timeCreated = timeCreated;
    }
    ...

The remainder of the ToDo class contains the usual getters, setters, and other entity methods.

The RequestBean class injects the EntityManager generated by the producer method, annotated with the @UserDatabase qualifier:

@ConversationScoped
@Stateful
public class RequestBean {

    @Inject
    @UserDatabase
    EntityManager em;

It then defines two methods, one that creates and persists a single ToDo list item, and another that retrieves all the ToDo items created so far by creating a query:

    public ToDo createToDo(String inputString) {
        ToDo toDo;
        Date currentTime = Calendar.getInstance().getTime();

        try {
            toDo = new ToDo();
            toDo.setTaskText(inputString);
            toDo.setTimeCreated(currentTime);
            em.persist(toDo);
            return toDo;
        } catch (Exception e) {
            throw new EJBException(e.getMessage());
        }
    }

    public List<ToDo> getToDos() {
        try {
             List<ToDo> toDos =
                    (List<ToDo>) em.createQuery(
                    "SELECT t FROM ToDo t ORDER BY t.timeCreated")
                    .getResultList();
            return toDos;
        } catch (Exception e) {
            throw new EJBException(e.getMessage());
        }
    }
}

The producerfields Facelets Pages and Managed Bean

The producerfields example has two Facelets pages, index.xhtml and todolist.xhtml. The simple form on the index.xhtml page asks the user only for the task. When the user clicks the Submit button, the listBean.createTask method is called. When the user clicks the Show Items button, the action specifies that the todolist.xhtml file should be displayed:

    <h:body>
        <h2>To Do List</h2>
        <p>Type a task to be completed.</p>
        <h:form id="todolist">
            <p><h:outputLabel value="Type a string: " for="inputString"/>
                <h:inputText id="inputString"
                             value="#{listBean.inputString}"/></p>
            <p><h:commandButton value="Submit"
                                action="#{listBean.createTask()}"/></p>
            <p><h:commandButton value="Show Items"
                                action="todolist"/></p>
        </h:form>
        ...
    </h:body>

The managed bean, web.ListBean, injects the ejb.RequestBean session bean. It declares the entity.ToDo entity and a list of the entity, along with the input string that it passes to the session bean. The inputString is annotated with the @NotNull Bean Validation constraint, so an attempt to submit an empty string results in an error.

@Named
@ConversationScoped
public class ListBean implements Serializable {

    ...
    @EJB
    private RequestBean request;
    @NotNull
    private String inputString;
    private ToDo toDo;
    private List<ToDo> toDos;

The createTask method called by the Submit button calls the createToDo method of RequestBean:

    public void createTask() {
        this.toDo = request.createToDo(inputString);
    }

The getToDos method, which is called by the todolist.xhtml page, calls the getToDos method of RequestBean:

public List<ToDo> getToDos() {
        return request.getToDos();
    }

To force the Facelets page to recognize an empty string as a null value and return an error, the web.xml file sets the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true:

<context-param>
  <param-name>
      javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
  </param-name>
  <param-value>true</param-value>
</context-param>

The todolist.xhtml page is a little more complicated than the index.html page. It contains a dataTable element that displays the contents of the ToDo list. The body of the page looks like this:

    <body>
        <h2>To Do List</h2>
        <h:form id="showlist">
            <h:dataTable var="toDo"
                         value="#{listBean.toDos}"
                         rules="all"
                         border="1"
                         cellpadding="5">
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Time Stamp" />
                    </f:facet>
                    <h:outputText value="#{toDo.timeCreated}" />
                </h:column>
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Task" />
                    </f:facet>
                    <h:outputText value="#{toDo.taskText}" />
                </h:column>
            </h:dataTable>
            <p><h:commandButton id="back" value="Back" action="index" /></p>
        </h:form>
    </body>

The value of the dataTable is listBean.toDos, the list returned by the managed bean’s getToDos method, which in turn calls the session bean’s getToDos method. Each row of the table displays the timeCreated and taskText fields of the individual task. Finally, a Back button returns the user to the index.xhtml page.

Running the producerfields Example

You can use either NetBeans IDE or Ant to build, package, deploy, and run the producerfields application.

To Build, Package, and Deploy the producerfields Example Using NetBeans IDE

  1. If the database server is not already running, start it by following the instructions in Starting and Stopping the Java DB Server.
  2. From the File menu, choose Open Project.
  3. In the Open Project dialog, navigate to:
    tut-install/examples/cdi/
  4. Select the producerfields folder.
  5. Select the Open as Main Project check box.
  6. Click Open Project.
  7. In the Projects tab, right-click the producerfields project and select Deploy.

To Build, Package, and Deploy the producerfields Example Using Ant

  1. If the database server is not already running, start it by following the instructions in Starting and Stopping the Java DB Server.
  2. In a terminal window, go to:
    tut-install/examples/cdi/producerfields/
  3. Type the following command:
    ant

    This command calls the default target, which builds and packages the application into a WAR file, producerfields.war, located in the dist directory.

  4. Type the following command:
    ant deploy

To Run the producerfields Example

  1. In a web browser, type the following URL:
    http://localhost:8080/producerfields

    The Create To Do List page opens.

  2. Type a string in the text field and click Submit.

    You can type additional strings and click Submit to create a task list with multiple items.

  3. Click the Show Items button.

    The To Do List page opens, showing the timestamp and text for each item you created.

  4. Click the Back button to return to the Create To Do List page.

    On this page, you can enter more items in the list.