Prev | Next

TOC | Index

J2EETM Developer's Guide
Clients


JavaServer PagesTM Components

A JavaServer PagesTM (JSP) component may use a JavaBeansTM component as a proxy to access an enterprise bean. The following diagram illustrates how these components work together:

FIGURE 7-2 JSP Client of an Enterprise Bean

The sections that follow show how to create a J2EE application with the following elements:

The Account.jsp and AccountBean.java files are in the doc/guides/ejb/examples/jsptobean directory. The AccountEJB.java source code is in the doc/guides/ejb/examples/account directory.

Setting Up the JSP Component's J2EE Application

The following figure shows the J2EE application that contains the JSP component. Stored in a .ear file, the J2EE application holds an EJB .jar file and a web component .war file. The EJB .jar file contains the AccountEJB entity bean described in the section, "A Bean-Managed Persistence Example". The .war file contains the JSP component (Account.jsp) and the JavaBeans component (AccountBean).

FIGURE 7-3 J2EE Application .ear File

The sections that follow describe how to create and package the web components, but first, you should set up the J2EE application:

If you need to review the instructions for performing the preceding tasks, see the section "Tips on Running the AccountEJB Example".

Writing the JSP File

This section briefly describes the JSP tags in the Account.jsp file. These tags are marked by bold font in the full listing of Account.jsp included at the end of this section. (For more information on writing JSP files, see the JavaServer Pages web site .)

The first JSP tag in the Account.jsp file specifies the JavaBeans component. The jsp:useBean tag creates a JavaBeans component by instantiating the AccountBean class, names the component accountBean, and indicates that the component will be available for the current HTTP session. Unlike the other JSP tags, the jsp:useBean tag is executed just once during the session-- when the end-user first accesses the Account.jsp page:

<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
The jsp:setProperty tag sets all of the property values in the accountBean to the parameters passed by the HTML form. For example, if the end-user selects the Debit radio button and clicks Submit, the action parameter is set to debit. This parameter value is sent to the web server, which assigns it to the action property value of the accountBean. The asterisk in the tag indicates that all properties will be set:

<jsp:setProperty name="accountBean" property="*" />
JSP scripting elements are enclosed as follows: <% element %>. The first scripting element declares the status variable:

<%! String status; %>
The next scripting element invokes processRequest method of the accountBean object. This method checks the action property value and invokes methods on the entity bean:

<% status = accountBean.processRequest(); %>
Near the bottom of the Account.jsp file, the status variable returned by the processRequest method is displayed:

<h3><b>Status :</b></h3> <%= status %>
In the HTML form tag, the action parameter indicates that the Account.jsp page is to be executed when the end-user clicks the form's Submit button. (Behind the scenes, the web server transforms the Account.jsp page into a servlet which it then executes.) Except for the jsp:useBean tag, every JSP tag and scripting element in the Account.jsp page is executed whenever the end-user clicks Submit:

<form method=POST action=Account.jsp>
Each jsp:getProperty tag fetches a property value from the accountBean. For example, the second jsp:getProperty tag retrieves the balance property from the accountBean. The balance is displayed in the text field of the HTML form. The next time the end-user clicks the Submit button, the value in the text field is sent to the web server as the balance parameter. The jsp:setProperty tag causes the web server to assign this parameter to the balance property of the accountBean. Here is the jsp:getProperty tag for the balance property:

<INPUT type=text name="balance"  size="8" 
value="<jsp:getProperty name="accountBean" property="balance" />">
The full listing for the Account.jsp file follows:

<html>
<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
<jsp:setProperty name="accountBean" property="*" />
<%! String status; %>

<% status = accountBean.processRequest(); %>

<html>
<head>
    <title>Account JSP</title>
</head>
<body background="back.gif">
<font size = 5 color="#CC0000">
<h1><b><center>Account JSP Example</center></b></h1>
<hr>
<br>
<form method=POST action=Account.jsp>
<br>

<br>Account ID  
<INPUT type=text name="id" size="8" 
value="<jsp:getProperty name="accountBean" property="id" />" >
Balance  
<INPUT type=text name="balance"  size="8" 
value="<jsp:getProperty name="accountBean" property="balance" />" >
<br>
First Name  
<INPUT type=text name="firstName" size="8" 
value="<jsp:getProperty name="accountBean" property="firstName" />">
Last Name   
<INPUT type=text name="lastName" "size=8" 
Value="<jsp:getProperty name="accountBean" property="lastName" />" 
><br>

<br>
<h2><b>Action :</b></h2>
  <INPUT type="radio" name="action" value="find">Find
  <INPUT type="radio" name="action" value="create">Create 
  <INPUT type="radio" name="action" value="debit">Debit
  <INPUT type="radio" name="action" value="credit">Credit
<br> 

<br>Amount  <INPUT type=text name="amount"><br>
<INPUT type=submit name="submit" value="Submit">

</form>
</FONT>
</body>
</html>

<hr>
<h3><b>Status :</b></h3> <%= status %>
</html>

Coding the JavaBeans Component

The following description of the AccountBean code is quite brief. For more information on coding JavaBeans components , see the JavaBeans home page.

The AccountBean JavaBeans component is created when the end-user first accesses the Account.jsp page. (This action is specified by the jsp:useBean tag in the Account.jsp file.) The AccountBean class accesses the entity bean implemented by the AccountEJB class. The constructor of the AccountBean class locates the entity bean's home interface by invoking the lookup method:

public AccountBean() {

   try {
       Context ic = new InitialContext();
       java.lang.Object objref =
          ic.lookup("java:comp/env/ejb/Account");
       accountHome = 
           (AccountHome) PortableRemoteObject.narrow(objref,
                                         AccountHome.class);
   } catch (Exception re) {
       System.err.println ("Couldn't locate Account Home");
       re.printStackTrace();
   }
   reset();
}
The end-user indicates the action parameter by selecting a radio button on the Account.jsp page. The web server assigns the parameter value to the action property of the AccountBean. Invoked by a scripting element in the Account.jsp page, the processRequest method of the AccountBean checks the value of the action property. If the action property is create, for example, the processRequest method creates a new entity bean. Here is the code for the processRequest method:

public String processRequest() {

   String  message = "";
   
   System.out.println("Process request called ");
   System.out.println(this);
   
   try {
   
     if( action.equals("create") ) {
   
        account = 
          accountHome.create(id, firstName, lastName, balance);
        message = "Created account `" + id + "`";
   
     }
     else if( action.equals("debit") ) {
       
        account = accountHome.findByPrimaryKey(id);
        account.debit(amount);
        loadFromEJB();
        message = "Debited account `" + id + "` by $" + amount;
     
     }
     else if( action.equals("credit") ) {
   
        account = accountHome.findByPrimaryKey(id);
        account.credit(amount);
        loadFromEJB();
        message = "Credited account `" + id + "` by $" + amount;
   
     }
     else if( action.equals("find") ) {
   
        account = accountHome.findByPrimaryKey(id);
        loadFromEJB();
        message = "Found account `" + id;
   
     }

   } // try
   
   catch (Exception e) {
     message = e.toString();
   }
   
   return message;
}
The state of the AccountBean instance mirrors that of the entity bean instance. Both instances contain these variables: id, firstName, lastName, and balance. The AccountBean changes the balance variable of the entity bean by invoking the debit and credit business methods. To refresh its state from the entity bean, the AccountBean invokes business methods such as getFirstName and getLastName. It invokes these getter methods in the private method loadFromEJB:

private void loadFromEJB() 
{
   System.out.println("Calling loadFromEJB()");
   try {
       setFirstName(account.getFirstName());
       setLastName(account.getLastName());
       setBalance(account.getBalance());
    } catch (Exception re) {
        System.err.println 
           ("Failed to load AccountBean from AccountEJB.");
        re.printStackTrace();
    }
}

Compiling the JavaBeans Component

When compiling AccountBean.java, you must include the j2ee.jar and ejb.jar files in the classpath. The ejb.jar file is required because it contains the class files for the Account and AccountHome interfaces-- types used by the AccountBean class. When you created the enterprise bean (AccountEJB) for the AccountJSPApp application, the tool inserted the ejb.jar file into the AccountJSPApp.ear file. To extract the ejb.jar file from the AccountJSPApp.ear file, follow these steps:

1. In the tree view, select the EJB .jar file for the AccountJSPApp application.

2. From the File menu, choose Save As.

3. Save the ejb.jar file in the examples/jsptobean directory.

To compile the JavaBeans component, change to the examples/jsptobean directory and execute these commands:

UNIX:

CPATH=.:$J2EE_HOME/lib/j2ee.jar:ejb.jar
javac -classpath "$CPATH" AccountBean.java 
Windows:

set CPATH=.;%J2EE_HOME%\lib\j2ee.jar;ejb.jar
javac -classpath %CPATH% AccountBean.java

Creating the JSP Component's .war File

To package the AccountBean.class and Account.jsp files in a .war file, you run the New Web Component Wizard of the Application Deployment Tool. To start the wizard, from the File menu choose New Web Component. The wizard displays the following dialog boxes. (You may skip any dialog boxes not listed here.)

WAR File General Properties Dialog Box:

a. In the combo box labelled "Web Component Will Go In," select AccountJSPApp.
b. In the WAR Display Name field, enter AccountWAR.
c. Click Add.
d. In the Add Content Files dialog box, choose the root directory containing the Account.jsp file (examples/jsptobean). You may either type the directory name in the Root Directory field or locate it by clicking Browse.
e. Select the Account.jsp file from the text area and click Add.
f. Click Next.
g. In the Add Class Files dialog box choose, the examples/jsptobean directory again.
h. Select the AccountBean.class file from the text area and click Add.
i. Click Finish.
j. Click Next.
Choose Component Type Dialog Box:

a. Select JSP.
b. Click Next.
Component General Properties Dialog Box:

a. In the JSP Filename combo box, select Account.jsp.
b. In the Web Component Display Name field, enter TheAccount.
c. Click Next.
Enterprise Bean References Dialog Box:

a. Click Add.
b. In the Coded Name column enter ejb/Account.
c. In the Type column select Entity.
d. In the Home column enter AccountHome.
e. In the Remote column enter Account.
f. Click Finish.

Specifying the Web Context Root

1. In the tree view select AccountJSPApp.

2. In the Web Context tabbed pane, enter AccountContextRoot in the ContextRoot column.

Specifying the JNDI Names

In the JNDI Names tabbed pane for the AccountJSPApp, enter the JNDI names shown in the following table:

TABLE 7-1 AccountJSPApp JNDI Names

Component/
Reference Name

JNDI Name

AccountBean MyAccount
jdbc/AccountDB jdbc/Cloudscape
ejb/Account MyAccount

Deploying the JSP Component's J2EE Application

1. From the Tools menu, choose Deploy Application.

2. In the first dialog box, do not select the checkbox labelled "Return Client Jar."

3. In the second dialog box, verify the JNDI names.

4. In the third dialog box, verify the context root.

Running the JSP Component

To run Account.jsp from your browser, specify the URL as follows, but replace <host> with the name of the machine that is running the J2EE server:

http://<host>:8000/AccountContextRoot/Account.jsp
To create a new account, follow these steps:

1. In the Account ID field, enter a three-digit integer.
2. In the Balance field, enter the intitial balance (for example, 100.00).
3. In the First Name and Last Name fields enter your name.
4. Under Action, select Create.
5. Click the Submit button.
To credit an account, perform the following tasks:

1. In the Account ID field, enter the three-digit account identifier.
2. In the Amount field, enter the credit amount (for example, 55.00).
3. Under Action, select Credit.
5. Click the Submit button.


Prev | Next

TOC | Index


Copyright © 2000 Sun Microsystems, Inc. All rights reserved.