The Java EE 5 Tutorial

Chapter 21 Getting Started with Enterprise Beans

This chapter shows how to develop, deploy, and run a simple Java EE application named converter. The purpose of converter is to calculate currency conversions between Japanese yen and Eurodollars. converter consists of an enterprise bean, which performs the calculations, and two types of clients: an application client and a web client.

    Here’s an overview of the steps you’ll follow in this chapter:

  1. Create the enterprise bean: ConverterBean.

  2. Create the application client: ConverterClient.

  3. Create the web client in converter-war.

  4. Deploy converter onto the server.

  5. Run the application client.

  6. Using a browser, run the web client.

Before proceeding, make sure that you’ve done the following:

Creating the Enterprise Bean

The enterprise bean in our example is a stateless session bean called ConverterBean. The source code for ConverterBean is in the tut-install/javaeetutorial5/examples/ejb/converter/converter-ejb/src/java/ directory.

    Creating ConverterBean requires these steps:

  1. Coding the bean’s business interface and class (the source code is provided)

  2. Compiling the source code with the Ant tool

Coding the Enterprise Bean

The enterprise bean in this example needs the following code:

Coding the Business Interface

The business interface defines the business methods that a client can call. The business methods are implemented in the enterprise bean class. The source code for the Converter remote business interface follows.

package com.sun.tutorial.javaee.ejb;

import java.math.BigDecimal;
import javax.ejb.Remote;

@Remote
public interface Converter {
    public BigDecimal dollarToYen(BigDecimal dollars);
    public BigDecimal yenToEuro(BigDecimal yen);
}

Note the @Remote annotation decorating the interface definition. This lets the container know that ConverterBean will be accessed by remote clients.

Coding the Enterprise Bean Class

The enterprise bean class for this example is called ConverterBean. This class implements the two business methods (dollarToYen and yenToEuro) that the Converter remote business interface defines. The source code for the ConverterBean class follows.

package com.sun.tutorial.javaee.ejb;

import java.math.BigDecimal;
import javax.ejb.*;

@Stateless
public class ConverterBean implements Converter {
    private BigDecimal yenRate = new BigDecimal("115.3100");
    private BigDecimal euroRate = new BigDecimal("0.0071");

    public BigDecimal dollarToYen(BigDecimal dollars) {
        BigDecimal result = dollars.multiply(yenRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
    }

    public BigDecimal yenToEuro(BigDecimal yen) {
        BigDecimal result = yen.multiply(euroRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
    }
}

Note the @Stateless annotation decorating the enterprise bean class. This lets the container know that ConverterBean is a stateless session bean.

Compiling and Packaging the converter Example

Now you are ready to compile the remote business interface (Converter.java) and the enterprise bean class (ConverterBean.java), and package the compiled classes into an enterprise bean JAR.

Compiling and Packaging the converter Example in NetBeans IDE

    Follow these instructions to build and package the converter example in NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/ejb/.

  3. Select the converter 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 converter project and select Build. You will see the output in the Output tab.

Compiling and Packaging the converter Example Using Ant

    To compile and package converter using Ant, do the following:

  1. In a terminal window, go to this directory:


    tut-install/javaeetutorial5/examples/ejb/converter/
  2. Type the following command:


    ant
    

This command calls the default task, which compiles the source files for the enterprise bean and the application client, placing the class files in the build subdirectories (not the src directory) of each submodule. Then the default task packages each submodule into the appropriate package file: converter-app-client.jar for the application client, converter-ejb.jar for the enterprise bean JAR, and converter-war.war for the web client. The web client in this example requires no compilation. For more information about the Ant tool, see Building the Examples.


Note –

When compiling the code, the preceding ant task includes the javaee.jar file in the classpath. This file resides in the lib directory of your Application Server installation. If you plan to use other tools to compile the source code for Java EE components, make sure that the classpath includes the javaee.jar file.


Creating the converter Application Client

An application client is a program written in the Java programming language. At runtime, the client program executes in a different virtual machine than the Application Server. For detailed information on the appclient command-line tool, see the man page at appclient(1M).

The application client in this example requires two JAR files. The first JAR file is for the Java EE component of the client. This JAR file contains the client’s deployment descriptor and class files; it is created when you run the New Application Client wizard. Defined by the Java EE Specification, this JAR file is portable across all compliant application servers.

The second JAR file contains all the classes that are required by the client program at runtime. These classes enable the client to access the enterprise beans that are running in the Application Server. The JAR file is retrieved before you run the application. Because this retrieved JAR file is not covered by the Java EE specification, it is implementation-specific, intended only for the Application Server.

The application client source code is in the ConverterClient.java file, which is in this directory:


tut-install/javaeetutorial5/examples/ejb/converter/converter-app-client/src/java/

You compiled this code along with the enterprise bean code in the section Compiling and Packaging the converter Example.

Coding the converter Application Client

The ConverterClient.java source code illustrates the basic tasks performed by the client of an enterprise bean:

Creating a Reference to an Enterprise Bean Instance

Java EE application clients refer to enterprise bean instances by annotating static fields with the @EJB annotation. The annotated static field represents the enterprise bean’s business interface, which will resolve to the session bean instance when the application client container injects the resource references at runtime.

@EJB
private static Converter converter;

The field is static because the client class runs in a static context.

Invoking a Business Method

Calling a business method is easy: you simply invoke the method on the injected Converter object. The EJB container will invoke the corresponding method on the ConverterBean instance that is running on the server. The client invokes the dollarToYen business method in the following lines of code.

BigDecimal param = new BigDecimal ("100.00");
BigDecimal amount = currencyConverter.dollarToYen(param);

ConverterClient Source Code

The full source code for the ConverterClient program follows.

package com.sun.tutorial.javaee.ejb;

import java.math.BigDecimal;
import javax.ejb.EJB;

public class ConverterClient {
    @EJB
    private static Converter converter;
    
    public ConverterClient(String[] args) {
    }

    public static void main(String[] args) {
        ConverterClient client = new ConverterClient(args);
        client.doConversion();
    }

    public void doConversion() {
        try {
            BigDecimal param = new BigDecimal("100.00");
            BigDecimal yenAmount = converter.dollarToYen(param);

            System.out.println("$" + param + " is " + yenAmount
                    + " Yen.");
            BigDecimal euroAmount = converter.yenToEuro(yenAmount);
            System.out.println(yenAmount + " Yen is " + euroAmount
                    + " Euro.");

            System.exit(0);
        } catch (Exception ex) {
            System.err.println("Caught an unexpected exception!");
            ex.printStackTrace();
        }
    }
}

Compiling the converter Application Client

The application client files are compiled at the same time as the enterprise bean files, as described in Compiling and Packaging the converter Example.

Creating the converter Web Client

The web client is contained in the JSP page tut-install/javaeetutorial5/examples/ejb/converter/converter-war/web/index.jsp. A JSP page is a text-based document that contains JSP elements, which construct dynamic content, and static template data, which can be expressed in any text-based format such as HTML, WML, and XML.

Coding the converter Web Client

The statements (in bold in the following code) for locating the business interface, creating an enterprise bean instance, and invoking a business method are nearly identical to those of the application client. The parameter of the lookup method is the only difference.

The classes needed by the client are declared using a JSP page directive (enclosed within the <%@ %> characters). Because locating the business interface and creating the enterprise bean are performed only once, this code appears in a JSP declaration (enclosed within the <%! %> characters) that contains the initialization method, jspInit, of the JSP page. The declaration is followed by standard HTML markup for creating a form that contains an input field. A scriptlet (enclosed within the <% %> characters) retrieves a parameter from the request and converts it to a BigDecimal object. Finally, a JSP scriptlet invokes the enterprise bean’s business methods, and JSP expressions (enclosed within the <%= %> characters) insert the results into the stream of data returned to the client.

<%@ page import="converter.ejb.Converter,
            java.math.*, javax.naming.*"%>

 <%!
    private Converter converter = null;
    public void jspInit() {
        try {
            InitialContext ic = new InitialContext();
            converter = (Converter)
                    ic.lookup(Converter.class.getName());
        } catch (Exception ex) {
            System.out.println("Couldn’t create converter bean."+
                    ex.getMessage());
        }
    }

    public void jspDestroy() {
        converter = null;
    }
%>
<html>
    <head>
        <title>Converter</title>
    </head>

    <body bgcolor="white">
        <h1>Converter</h1>
        <hr>
        <p>Enter an amount to convert:</p>
        <form method="get">
            <input type="text" name="amount" size="25">
            <br>
            <p>
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">
        </form>

        <%
            String amount = request.getParameter("amount");
            if ( amount != null && amount.length() > 0 ) {
                BigDecimal d = new BigDecimal(amount);

                BigDecimal yenAmount = converter.dollarToYen(d);
        %>
        <p>
        <%= amount %> dollars are  <%= yenAmount %>  Yen.
        <p>
        <%
                BigDecimal euroAmount =
                        converter.yenToEuro(yenAmount);
        %>
        <%= amount %> Yen are <%= euroAmount %>  Euro.
        <%
            }
        %>
    </body>
</html>

Compiling the converter Web Client

The Application Server automatically compiles web clients that are JSP pages. If the web client were a servlet, you would have to compile it.

Deploying the converter Java EE Application

Now that the Java EE application contains the components, it is ready for deployment. You can deploy the application using either NetBeans IDE or Ant.

Deploying the converter Example Using NetBeans IDE

    Follow these instructions to deploy the converter example to your Application Server instance using NetBeans IDE.

  1. In NetBeans IDE, make sure the converter application is open.

  2. In the Projects tab, right-click the converter project and select Undeploy and Deploy. You will see the output in the Output tab.

Deploying the converter Example Using Ant

To deploy converter.ear using Ant, run the deploy task.


ant deploy

converter.ear will be deployed to the Application Server.

Running the converter Application Client

When you run the application client, the application client container first injects the resources specified in the client and then runs the client. You can run the application client using either NetBeans IDE or Ant.

Running the converter Application Client Using NetBeans IDE

    Follow these instructions to run the application client using NetBeans IDE.

  1. In NetBeans IDE, make sure the converter application is open.

  2. In the Projects tab, right-click the converter project and select Run. You will see the following output in the Output tab:


    ...
    $100.00 is 11258.00 Yen.
    11258.00 Yen is 78.81 Euro.
    ...

Running the converter Application Client Using Ant

    To run the application client using Ant, perform the following steps.

  1. In a terminal window, go to this directory:


    tut-install/javaeetutorial5/examples/ejb/converter/
  2. Type the following command:


    ant run
    

    This task will retrieve the application client JAR, converterClient.jar and run the retrieved client JAR. converterClient.jar contains the application client class and the support classes needed to access ConverterBean. Although you are using Ant to run the client, this task is the equivalent of running:


    appclient -client client-jar/converterClient.jar
    
  3. In the terminal window, the client displays these lines:


    ...
    $100.00 is 11531.00 Yen.
    11531.00 Yen is 81.88 Euro.
    ...

Running the converter Web Client

To run the web client, point your browser at the following URL. Replace host with the name of the host running the Application Server. If your browser is running on the same host as the Application Server, you can replace host with localhost.


http://host:8080/converter

After entering 100 in the input field and clicking Submit, you should see the screen shown in Figure 21–1.

Figure 21–1 converter Web Client

Screenshot showing the converter web client.

Modifying the Java EE Application

The Application Server supports iterative development. Whenever you make a change to a Java EE application, you must redeploy the application.

Modifying a Class File

    To modify a class file in an enterprise bean, you change the source code, recompile it, and redeploy the application. For example, if you want to change the exchange rate in the dollarToYen business method of the ConverterBean class, you would follow these steps.

  1. Edit ConverterBean.java.

  2. Recompile ConverterBean.java.

    1. In a terminal window, go to the tut-install/javaeetutorial5/examples/ejb/converter/ subdirectory.

    2. Type the following command:


      ant
      

      This command runs the default task, which repackages the entire application (application client, enterprise bean JAR, and web client).

  3. Type the following command:


    ant deploy
    

To modify the contents of a WAR file, or to modify the application client, follow the preceding steps.