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

A Singleton Session Bean Example: counter

Creating a Singleton Session Bean

Initializing Singleton Session Beans

Managing Concurrent Access in a Singleton Session Bean

Handling Errors in a Singleton Session Bean

The Architecture of the counter Example

Running the counter Example

To Run the counter Example Using NetBeans IDE

To Run the counter Example Using Ant

A Web Service Example: helloservice

The Web Service Endpoint Implementation Class

Stateless Session Bean Implementation Class

Running the helloservice Example

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

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

To Test the Service without a Client

Using the Timer Service

Creating Calendar-Based Timer Expressions

Specifying Multiple Values in Calendar Expressions

Programmatic Timers

The @Timeout Method

Creating Programmatic Timers

Automatic Timers

Canceling and Saving Timers

Getting Timer Information

Transactions and Timers

The timersession Example

Running the timersession Example

To Run the timersession Example Using NetBeans IDE

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

To Run the Web Client

Handling Exceptions

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

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 cart Example

The cart example represents a shopping cart in an online bookstore and uses a stateful session bean to manage the operations of the shopping cart. The bean’s client can add a book to the cart, remove a book, or retrieve the cart’s contents. To assemble cart, you need the following code:

  • Session bean class (CartBean)

  • Remote business interface (Cart)

All session beans require a session bean class. All enterprise beans that permit remote access must have a remote business interface. To meet the needs of a specific application, an enterprise bean may also need some helper classes. The CartBean session bean uses two helper classes, BookException and IdVerifier, which are discussed in the section Helper Classes.

The source code for this example is in the tut-install/examples/ejb/cart/ directory.

The Business Interface

The Cart business interface is a plain Java interface that defines all the business methods implemented in the bean class. If the bean class implements a single interface, that interface is assumed to the business interface. The business interface is a local interface unless it is annotated with the javax.ejb.Remote annotation; the javax.ejb.Local annotation is optional in this case.

The bean class may implement more than one interface. In that case, the business interfaces must either be explicitly annotated @Local or @Remote or be specified by decorating the bean class with @Local or @Remote. However, the following interfaces are excluded when determining whether the bean class implements more than one interface:

  • java.io.Serializable

  • java.io.Externalizable

  • Any of the interfaces defined by the javax.ejb package

The source code for the Cart business interface follows:

package cart.ejb;

import cart.util.BookException;
import java.util.List;
import javax.ejb.Remote;

@Remote
public interface Cart {
    public void initialize(String person) throws BookException;
    public void initialize(String person, String id)
         throws BookException;
    public void addBook(String title);
    public void removeBook(String title) throws BookException;
    public List<String> getContents();
    public void remove();
}

Session Bean Class

The session bean class for this example is called CartBean. Like any stateful session bean, the CartBean class must meet the following requirements.

  • The class is annotated @Stateful.

  • The class implements the business methods defined in the business interface.

Stateful session beans also may

  • Implement the business interface, a plain Java interface. It is good practice to implement the bean’s business interface.

  • Implement any optional lifecycle callback methods, annotated @PostConstruct, @PreDestroy, @PostActivate, and @PrePassivate.

  • Implement any optional business methods annotated @Remove.

The source code for the CartBean class follows:

package cart.ejb;

import cart.util.BookException;
import cart.util.IdVerifier;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;

@Stateful
public class CartBean implements Cart {
    String customerName;
    String customerId;
    List<String> contents;

    public void initialize(String person) throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {
            customerName = person;
        }

        customerId = "0";
        contents = new ArrayList<String>();
    }

    public void initialize(String person, String id)
                 throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {

            customerName = person;
        }

        IdVerifier idChecker = new IdVerifier();

        if (idChecker.validate(id)) {
            customerId = id;
        } else {
            throw new BookException("Invalid id: " + id);
        }

        contents = new ArrayList<String>();
    }

    public void addBook(String title) {
        contents.add(title);
    }

    public void removeBook(String title) throws BookException {
        boolean result = contents.remove(title);
        if (result == false) {
            throw new BookException(title + " not in cart.");
        }
    }

    public List<String> getContents() {
        return contents;
    }

    @Remove
    public void remove() {
        contents = null;
    }
}

Lifecycle Callback Methods

A method in the bean class may be declared as a lifecycle callback method by annotating the method with the following annotations:

  • javax.annotation.PostConstruct: Methods annotated with @PostConstruct are invoked by the container on newly constructed bean instances after all dependency injection has completed and before the first business method is invoked on the enterprise bean.

  • javax.annotation.PreDestroy: Methods annotated with @PreDestroy are invoked after any method annotated @Remove has completed and before the container removes the enterprise bean instance.

  • javax.ejb.PostActivate: Methods annotated with @PostActivate are invoked by the container after the container moves the bean from secondary storage to active status.

  • javax.ejb.PrePassivate: Methods annotated with @PrePassivate are invoked by the container before it passivates the enterprise bean, meaning that the container temporarily removes the bean from the environment and saves it to secondary storage.

Lifecycle callback methods must return void and have no parameters.

Business Methods

The primary purpose of a session bean is to run business tasks for the client. The client invokes business methods on the object reference it gets from dependency injection or JNDI lookup. From the client’s perspective, the business methods appear to run locally, although they run remotely in the session bean. The following code snippet shows how the CartClient program invokes the business methods:

cart.create("Duke DeEarl", "123");
...
cart.addBook("Bel Canto");
 ...
List<String> bookList = cart.getContents();
...
cart.removeBook("Gravity's Rainbow");

The CartBean class implements the business methods in the following code:

public void addBook(String title) {
   contents.addElement(title);
}

public void removeBook(String title) throws BookException {
   boolean result = contents.remove(title);
   if (result == false) {
      throw new BookException(title + "not in cart.");
   }
}

public List<String> getContents() {
   return contents;
}

The signature of a business method must conform to these rules.

  • The method name must not begin with ejb, to avoid conflicts with callback methods defined by the EJB architecture. For example, you cannot call a business method ejbCreate or ejbActivate.

  • The access control modifier must be public.

  • If the bean allows remote access through a remote business interface, the arguments and return types must be legal types for the Java Remote Method Invocation (RMI) API.

  • If the bean is a web service endpoint, the arguments and return types for the methods annotated @WebMethod must be legal types for JAX-WS.

  • The modifier must not be static or final.

The throws clause can include exceptions that you define for your application. The removeBook method, for example, throws a BookException if the book is not in the cart.

To indicate a system-level problem, such as the inability to connect to a database, a business method should throw a javax.ejb.EJBException. The container will not wrap application exceptions, such as BookException. Because EJBException is a subclass of RuntimeException, you do not need to include it in the throws clause of the business method.

The @Remove Method

Business methods annotated with javax.ejb.Remove in the stateful session bean class can be invoked by enterprise bean clients to remove the bean instance. The container will remove the enterprise bean after a @Remove method completes, either normally or abnormally.

In CartBean, the remove method is a @Remove method:

@Remove
public void remove() {
    contents = null;
}

Helper Classes

The CartBean session bean has two helper classes: BookException and IdVerifier. The BookException is thrown by the removeBook method, and the IdVerifier validates the customerId in one of the create methods. Helper classes may reside in an EJB JAR file that contains the enterprise bean class, a WAR file if the enterprise bean is packaged within a WAR, or in an EAR that contains an EJB JAR or a WAR file that contains an enterprise bean.

Running the cart Example

Now you are ready to compile the remote interface (Cart.java), the home interface (CartHome.java), the enterprise bean class (CartBean.java), the client class (CartClient.java), and the helper classes (BookException.java and IdVerifier.java). Follow these steps.

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

To Run the cart Example Using NetBeans IDE

  1. From the File menu, choose Open Project.
  2. In the Open Project dialog, navigate to:
    tut-install/examples/ejb/
  3. Select the cart folder.
  4. Select the Open as Main Project and Open Required Projects check boxes.
  5. Click Open Project.
  6. In the Projects tab, right-click the cart project and select Deploy.

    This builds and packages the application into cart.ear, located in tut-install/examples/ejb/cart/dist/, and deploys this EAR file to your GlassFish Server instance.

  7. From the Run menu, choose Run Main Project.

    You will see the output of the cart application client in the Output pane:

    ...
    Retrieving book title from cart: Infinite Jest
    Retrieving book title from cart: Bel Canto
    Retrieving book title from cart: Kafka on the Shore
    Removing "Gravity's Rainbow" from cart.
    Caught a BookException: "Gravity's Rainbow" not in cart.
    Java Result: 1
    run-cart-app-client:
    run-nb:
    BUILD SUCCESSFUL (total time: 14 seconds)

To Run the cart Example Using Ant

  1. In a terminal window, go to:
    tut-install/examples/ejb/cart/
  2. Type the following command:
    ant

    This command calls the default target, which builds and packages the application into an EAR file, cart.ear, located in the dist directory.

  3. Type the following command:
    ant deploy

    The cart.ear file is deployed to the GlassFish Server.

  4. Type the following command:
    ant run

    This task retrieves the application client JAR, cartClient.jar, and runs the application client. The client JAR, cartClient.jar, contains the application client class, the helper class BookException, and the Cart business interface.

    This task is equivalent to running the following command:

    appclient -client cartClient.jar

    When you run the client, the application client container injects any component references declared in the application client class, in this case the reference to the Cart enterprise bean.

The all Task

As a convenience, the all task will build, package, deploy, and run the application. To do this, enter the following command:

ant all