★ wanayoo — archive 1999 http://developer.java.sun.com/developer/onlineTraining/J2EE/Intro/session.htmlNouvelle recherche | Portail wanayoo
Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
 
Training Index

Writing Enterprise Applications
Lesson 1: A Simple Session Bean

[J2EE TECH CENTER] [<<BACK] [CONTENTS] [NEXT>>]

This lesson introduces you to J2EE applications programming, and the J2EE Reference Implementation by showing you how to write a simple thin-client multitiered enterprise application.

The J2EE Reference Implementation is a non-commercial operational definition of the J2EE platform and specification made freely available by Sun Microsystems for demonstrations, prototyping, and educational uses. It comes with the J2EE application server, web server, database, J2EE APIs, Java Plug-In, and a full-range of development and deployment tools. You will become acquainted with many of these features and tools as you work through the lessons in this tutorial.

Lesson 1 Zip file


Example Thin-Client Multitiered Application

The example thin-client multitiered application for this lesson accepts user input through an HTML form that invokes a servlet. The servlet uses Java Naming and Directory InterfaceTM (JNDI) to look up a session Bean to perform a calculation on its behalf. Upon receiving the results of the calculation, the servlet returns the calculation value to the end user in an HTML page.

This example is a thin-client application because the servlet does not execute any business logic. The simple calculation is performed by a session Bean executing on the J2EE application server. So, the client is thin because it does not handle the processing; the session Bean does.

The thin-client server is the first tier in this multitier example, and the application server is the second tier. Multitier or three-tier architecture extends the standard two-tier client and server model by placing a multithreaded application server between the client and database.

While this lesson uses only two of the three tiers, Lesson 2 expands this same example to access the database server in the third tier. Later lessons adapt the example to use JavaServerTM Pages and Extensible Markup Language (XML).

J2EE Software and Setup

To run the lesson examples, you need to download and install the Java 2 SDK Enterprise Edition (J2EE), Beta Release and Java 2 SDK, Standard Edition. The instructions in this tutorial assume these are installed in a J2EE directory in monicap's home directory as follows:

Note: Everywhere you see monicap used in a path name, please change it to your own user name.
Unix:
  /home/monicap/J2EE/j2sdkee-beta 
  /home/monicap/J2EE/jdk1.2.2

Windows:
  \home\monicap\J2EE\j2sdkee-beta
  \home\monicap\J2EE\jdk1.2.2
The j2sdkee-beta download has the J2EE application server, Cloudscape database, HTTP, HTTP over secure socket layer (SSL), development and deployment tools, and the Java APIs for the Enterprise. To use these features, set your path and class path variables to point to the following files:

Path Settings

Path settings make the development and deployment tools accessible from anywhere on your system.
Unix:
  /home/monicap/J2EE/jdk1.2.2/bin
  /home/monicap/J2EE/j2sdkee-beta/bin

Windows:
  \home\monicap\J2EE\jdk1.2.2\bin
  \home\monicap\J2EE\j2sdkee-beta\bin

Class Path Settings

Class path settings tell the Java 2, Enterprise and Standard Edition, development and deployment tools where to find the various class libraries they use.
Unix:
  /home/monicap/J2EE/j2skdee-beta/lib/j2ee.jar

Windows:
  \home\monicap\J2EE\j2skdee-beta\lib\j2ee.jar

J2EE Application Components

J2EE applications programmers write J2EE application components. A J2EE application component is a self-contained functional software unit that is added to and interfaces with other application components. The applications programmer or an assembler use the Deployer tool to assemble application components into a complete J2EE application.

The example for this lesson has two application components: (1) An HTML page and servlet, and (2) A session Bean. You will create the components, assemble them into a complete J2EE application, and deploy and run the application in this lesson.

An application component can consist of a number of elements. For example, the HTML page and servlet are one application component because they work together. The HTML form invokes the servlet, and the servlet retrieves the data entered onto the form embedded in the HTML page.

Also, the session Bean is one application component that consists of the CalcBean.class session Bean, and its home (CalcHome.class) and remote (Calc.class) interfaces. The home and remote interfaces are the means by which client programs access the session Bean methods.

The figure below shows how the bonus.html page looks when displayed to the user. The bonus.html file has two data fields so the user can enter a social security number and a multiplier. When the user clicks the Submit button, BonusServlet retrieves the end user data, looks up the session Bean, and passes the user data to the session Bean. The session Bean calculates a bonus and returns the bonus value to the servlet. The servlet then displays the bonus value to the end user in an HTML page.

This next diagram shows how data flows between the browser and the session Bean. The session Bean executes in the J2EE application server.

Create the HTML File

The bonus.html code appears below. The interesting thing about the form HTML code is the pathname used to invoke the BonusServlet.class. It includes a BonusRoot directory.

The BonusRoot directory is specified during component assembly. During deployment, the BonusRoot directory is created and the HTML file placed in it with the servlet class file placed in the servlet directory below it. This point is illustrated by the diagram on the left.

HTML Code
The example assumes this file is in the /home/monicap/J2EE/ClientCode directory on Unix. Here and hereafter, Windows users can reverse the slashes to get the correct directory pathname for their platform.
<HTML>
<BODY BGCOLOR = "WHITE">
<BLOCKQUOTE>
<H3>Bonus Calculation</H3>
<FORM METHOD="GET" ACTION="/old?u=http%3A%2F%2Fdeveloper.java.sun.com%2FBonusRoot%2Fservlet%2FBonusServlet&y=1999">
<P>
Enter social security Number:
<P>
<INPUT TYPE="TEXT" NAME="SOCSEC"></INPUT>
<P>
Enter Multiplier:
<P>
<INPUT TYPE="TEXT" NAME="MULTIPLIER"></INPUT>
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET">
</FORM>
</BLOCKQUOTE>
</BODY>
</HTML>

Create the Servlet

The servlet code retrieves the user data, looks up the session Bean, passes the data to the session Bean, and upon receiving a value back from the session Bean creates an HTML page to display the returned value to the user.

A discussion of the code (shown in its entirety in the Servlet Code section below) begins with the import statements:

  • javax.servlet, which contains generic (protocol-independent) servlet classes. The HttpServlet class uses the ServletException class in this package to indicate a servlet problem.

  • javax.servlet.http, which contains HTTP servlet classes. The HttpServlet class is in this package.

  • java.io for system input and output. The HttpServlet class uses the IOException class in this package to signal that an input or output exception of some kind has occurred.

  • javax.naming for using the Java naming and directory interface APIs to look up the session Bean home interface.

  • javax.rmi.PortableRemoteObject for looking up the session Bean home interface and making its remote server object ready for communications.

The BonusServlet.init method looks up the session Bean home interface and creates its instance. The lookup method uses the JNDI name specified during component assembly (calcs) to get a reference to the home interface by its name. The next line passes the reference and the home interface class to the PortableRemoteObject.narrow method to be sure the reference can be cast to type CalcHome.

  InitialContext ctx = new InitialContext();
  Object objref = ctx.lookup("calcs");
  homecalc = (CalcHome)PortableRemoteObject.narrow(
             objref,
             CalcHome.class);
The parameter list for the doGet method takes a request and response object. The browser sends a request to the servlet and the servlet sends a response back to the browser. The method implementation accesses information in the request object to find out who made the request, what form the request data is in, and which HTTP headers were sent, and uses the response object to create an HTML page in response to the browser's request.

The doGet method throws an IOException if there is an input or output problem when it handles the request, and a ServletException if the request could not be handled.

To calculate the bonus value, the doGet method creates the home interface and calls its calcBonus method.

  public void doGet (HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException
  {
    PrintWriter out;
    response.setContentType("text/html");
    String title = "EJB Example";
    out = response.getWriter();
    out.println("<HTML><HEAD><TITLE>)
    out.println(title);
    out.println("</TITLE></HEAD><BODY>");


    try{
//Retrieve Bonus and Social Security Information
      String strMult = request.getParameter(
                                   "MULTIPLIER");
      Integer integerMult = new Integer(strMult);
      multiplier = integerMult.intValue();
      socsec = request.getParameter("SOCSEC");

//Calculate bonus
      double bonus = 100.00;
      theCalculation = homecalc.create();
      calc = theCalculation.calcBonus(multiplier, bonus);
    }catch(Exception CreateException){
        CreateException.printStackTrace();
    }

//Display Data
    out.println("<H1>Bonus Calculation</H1>");
    out.println("<P>Soc Sec: " + socsec + "<P>");
    out.println("<P>Multiplier: " + multiplier + "<P>");
    out.println("<P>Bonus Amount: " + calc + "<P>");
    out.println("</BODY></HTML>");
    out.close();
  }
Servlet Code
Here is the full BonusServlet code. The example assumes this file is in the /home/monicap/J2EE/ClientCode directory on Unix.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import Beans.*;

public class BonusServlet extends HttpServlet {
  CalcHome homecalc;
  Calc theCalculation;

  String socsec = null;
  int multiplier = 0;
  double calc = 0.0;

  public void init(ServletConfig config) 
		throws ServletException{

//Look up home interface
    try{
        InitialContext ctx = new InitialContext();
        Object objref = ctx.lookup("calcs");
        homecalc = 
            (CalcHome)PortableRemoteObject.narrow(
		objref, 
		CalcHome.class);
   } catch (Exception NamingException) {
        NamingException.printStackTrace();
   }
  }

  public void doGet (HttpServletRequest request, 
	     HttpServletResponse response) 
	     throws ServletException, IOException
  {
    PrintWriter out;
    response.setContentType("text/html");
    String title = "EJB Example";
    out = response.getWriter();
    out.println("<HTML><HEAD><TITLE>
    out.println(title);
    out.println("</TITLE></HEAD><BODY>");


    try{
//Retrieve Bonus and Social Security Information
   String strMult = 
           request.getParameter("MULTIPLIER");
   Integer integerMult = new Integer(strMult);
   multiplier = integerMult.intValue();
   socsec = request.getParameter("SOCSEC");

//Calculate bonus
    double bonus = 100.00;
    theCalculation = homecalc.create();
    calc = 
     theCalculation.calcBonus(multiplier, bonus);
    }catch(Exception CreateException){
       CreateException.printStackTrace();
    }

//Display Data
    out.println("<H1>Bonus Calculation</H1>");
    out.println("<P>Soc Sec: " + socsec + "<P>");
    out.println("<P>Multiplier: " + multiplier + "<P>");
    out.println("<P>Bonus Amount: " + calc + "<P>");
    out.println("</BODY></HTML>");
    out.close();
  }

  public void destroy() {
    System.out.println("Destroy");
  }
}

Create the Session Bean

A session Bean represents a transient conversation with a client. If the server or client crashes, the session Bean and its data are gone. In contrast, entity Beans are persistent and represent data in a database. If the server or client crashes, the underlying services ensure that the entity Bean data is saved.

Because the enterprise Bean performs a simple calculation at the request of BonusServlet and the calculation can be reinitiated in the event of a crash, it makes sense to use a session Bean in this example.

The diagram shows how the application components work as a complete J2EE application once they are assembled and deployed. The container, shown in the shaded box, is the interface between the session Bean and the low-level platform-specific functionality that supports the session Bean. The container is created during deployment.

The next sections show the session Bean code. The example assumes these files are in the /home/monicap/J2EE/Beans directory on Unix.

Note: While this example shows how to write the example session Bean, it is also possible to purchase enterprise Beans from a provider and assemble them into a J2EE application.
CalcHome
BonusServlet does not work directly with the session Bean, but creates an instance of its home interface. The home interface extends EJBHome and has a create method for creating the session Bean in its container.

The CreateException is thrown if the session Bean cannot be created, and a RemoteException is thrown if a communications-related exception occurs during the execution of a remote method.

package Beans; 

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface CalcHome extends EJBHome {
  Calc create() throws CreateException, 
                           RemoteException;
}
Calc
When the home interface is created, the J2EE application server creates the remote interface and session Bean. The remote interface extends EJBObject and declares the calcBonus method for calculating the bonus value. This method is required to throw javax.rmi.RemoteException, and is implemented by the CalcBean class.
package Beans;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Calc extends EJBObject {
  public double calcBonus(
            int multiplier, double bonus)
                throws RemoteException;
}
CalcBean
The session Bean class implements the SessionBean interface and provides behavior for the calcBonus method. The SetSessionContext and ejbCreate methods are called in that order by the container after BonusServlet calls the create method in CalcHome.

The empty methods are from the SessionBean interface. These methods are called by the Bean's container. You do not need to provide behavior for these methods unless you need additional functionality when the Bean is, for example, created or removed from its container.

package Beans;

import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class CalcBean implements SessionBean {

  public double calcBonus(int multiplier, 
		double bonus) {
    double calc = (multiplier*bonus);
    return calc;
  }

//These methods are described in more
//detail in Lesson 2
  public void ejbCreate() { }
  public void setSessionContext(
		SessionContext ctx) { }
  public void ejbRemove() { }
  public void ejbActivate() { }
  public void ejbPassivate() { }
  public void ejbLoad() { }
  public void ejbStore() { }
}

Compile the Session Bean and Servlet

To save on typing, the easiest way to compile the session Bean and BonusServlet code is with a script (on Unix) or a batch file (on Windows).

Compile the Session Bean

Unix:
  #!/bin/sh
  cd /home/monicap/J2EE 
  J2EE_HOME=/export/home/monicap/J2EE/j2sdkee-beta
  CPATH=.:$J2EE_HOME/lib/j2ee.jar
  javac -d . -classpath "$CPATH" Beans/CalcBean.java 
		Beans/CalcHome.java Beans/Calc.java 

Windows:
  cd \home\monicap\J2EE 
  set J2EE_HOME=\export\home\monicap\J2EE\j2sdkee-beta
  set CPATH=.;%J2EE_HOME%\lib\j2ee.jar
  javac -d . -classpath %CPATH% Beans/CalcBean.java 
		Beans/CalcHome.java Beans/Calc.java 

Compile the Servlet

Unix:
 cd /home/monicap/J2EE/ClientCode 
 J2EE_HOME=/export/home/monicap/J2EE/j2sdkee-beta
 CPATH=.:$J2EE_HOME/lib/j2ee.jar:/export
         /home/monicap/J2EE:
	/export/home/monicap/J2EE/Beans
 javac -d . -classpath "$CPATH" BonusServlet.java 

Windows:
 cd \home\monicap\J2EE\ClientCode 
 J2EE_HOME=\export\home\monicap\J2EE\j2sdkee-beta
 CPATH=.;%J2EE_HOME%\lib\j2ee.jar:\export
                       \home\monicap\J2EE:
	   \export\home\monicap\J2EE/Beans
 javac -d . -classpath %CPATH% BonusServlet.java 

Start the J2EE Application Server

You need to start the J2EE application server to deploy and run the example. The command to start the server is in the bin directory under your J2EE installation. If you have your path set up to read the bin directory, go to the J2EE-beta directory (so your live version matches what you see in this text) and type:
  j2ee -verbose
If that does not work, type this from the J2EE-beta directory:
Unix:
  j2sdkee-beta/bin/j2ee -verbose

Windows:
  j2sdkee-beta\bin\j2ee -verbose
The verbose option prints informational messages to the command line as the server starts up. When you see J2EE server startup complete, you can start the deployer tool.

Start the Deployer Tool

To assemble and deploy the J2EE application, you have to start the deployer tool. If you have your path set up to read the bin directoy, go to the J2EE-beta directory (so your live version matches what you see in this text) and type:
  deployertool
If that does not work, type this from the J2EE-beta directory:
Unix:
  j2sdkee-beta/bin/deploytool

Windows:
  j2sdkee-beta\bin\deploytool

The deployer tool has four main windows. The Local Applications window displays J2EE applications and their components. The Inspecting window displays information on the selected application or components. The Servers window tells you the J2EE application server is running on the local host. And the Server Applications window tells you which applications have been installed.

As you go through the steps to assemble the example J2EE application, you will see the Local Applications, Inspecting, and Server Applications windows display information.


Note: At the bottom of the Application Deployment tool is a Server Applications window and a grayed Uninstall button next to it. At the end of this lesson after you deploy the application, you will see the application listed in the Server Applications window. You can click Uninstall to uninstall the application, make changes, and redeploy it without having to stop and restart the J2EE application server.

Assemble the J2EE Application

To assemble a J2EE application, you first create an Enterprise Archive (EAR) file and then add the application components to it. In this example, there are the following two application components:
  • A Web Archive (WAR) file that contains the bonus.html and BonusServlet.class files.

  • A Java Archive (JAR) file that contains the three session Bean files: Calc.class, CalcHome.class, and CalcBean.class.
Here is a summary of the assembly steps, which are discussed in more detail below.
  1. Create J2EE application EAR file (BonusApp.ear).
  2. Create session Bean JAR file (CalcBean.jar).
  3. Add session Bean JAR file to EAR file.
  4. Create web component WAR file (Bonus.war).
  5. Add WAR file to EAR file.
  6. Specify JNDI name for session Bean (calcs).
  7. Specify Root Context (BonusRoot).
    Create J2EE Application EAR file
    In the Step 1 of 2 dialog box, select New from the Applications menu. In the dialog box that appears, type BonusApp and click Next. BonusApp is the display name for this application. The display name is the name that appears in the Deployer tool informational windows.

    In the Step 2 of 2 dialog box, click Browse.

    In the Choose File dialog box, select the J2EE directory, type BonusApp.ear in the file name: field, and click Choose file.

    In the Step 2 of 2 dialog box, click Done.

    The BonusApp.ear file is now listed under Local Applications, and the Inspector window to the right shows the display name, location, and meta information for BonusApp.ear. The meta information describes the JAR file and J2EE application, and provides runtime information about the application.

    Create Session Bean JAR File
    From the Application menu, select New EJB JAR. The Step 1 of 12 dialog box summarizes the steps you are about to take. After reading it over, click Next.

    Note: After creating the EAR file, you should be familiar with the Deployer Tool user interface. So, to facilitate uploading and downloading time, the steps use minimal screen captures, and instead provide a text-based representation of what you need to do.

    In the Step 2 of 12 dialog box, specify the directory where the session Bean class package is located. In this example, that directory is J2EE. Click Next.

    Enterprise Bean Wizard - Step 2 of 12
      Base directory:
       /export/home/monicap/J2EE
    
    In the Step 3 of 12 dialog box, enter the Bean classes including the package names as shown. On the right click the Session and Stateless radio buttons under Bean type. When you are finished, click Next.
    Enterprise Bean Wizard - Step 3 of 12
      Class name
        Beans.CalcBean
    
      Home interface
        Beans.CalcHome
    
      Remote interface
        Beans.Calc
    
      Display Name
        CalcBean
    
      Description
        A simple session Bean that calculates a bonus.
        It has one method.
    
    Click Next to bypass the Step 5 of 12 Environment Entries (java.util.Properties), 6 of 12 EJBs Referenced in Code, 7 of 12 Resource Factories, 8 of 12 Role Names, and 9 of 12 Transactions dialog boxes. This simple session Bean does not use properties (environment settings), does not reference other enterprise Beans (resource factories), does not look up a database or JavaMailTM session object, does not use security roles, and has no distributed transactions. In the Step 10 of 12 dialog box, select Don't add another ejb descriptor because no other enterprise Bean will be added to the JAR file. Click Next.
    Enterprise Bean Wizard - Step 10 of 12
      /export/home/monicap/J2EE
    
    In the Step 11 of 12 dialog box, specify the JAR file name and location, the display name (the name that appears when when the JAR file is added to BonusApp in the Local Applications window, and provide a description of the JAR file contents. The Contents window should show the three class files that make up the CalcBean session Bean. Click Next.
    Enterprise Bean Wizard - Step 11 of 12
    
      Location:
        /export/home/monicap/J2EE/CalcBean.jar
      Display Name:
        CalcBean.jar
      Description:
        This JAR file contains the CalcBean session Bean.
      Contents:
        CalcBean.class
        CalcHome.class
        Calc.class
    
    Click OK on the message box that pops up to tell you the JAR file was created in the specified directory. The Step 12 of 12 dialog box shows the Extensible Markup Language (XML) desciptor that was created for the JAR file. The XML file contains deployment information, which includes structural information about the Bean classes, and whatever attributes you specified in the previous screens. Click Done.

    Click Yes on the Question box that pops up to ask you if you want to add the newly created EJB JAR file to the application.

    To verify the JAR file was indeed added, go to the Local Applications window and double click BonusApp. You will see the display name you gave the JAR file. Click the key graphic to see the display name you gave the session Bean. The screen capture shows General inspection information in the right window for the BonusApp. You can see General inspection information for CalcBeanJar or CalcBean by clicking on them.

    Create Web Component WAR File
    Web clients (HTML pages and their corresponding servlets, and JavaServer Pages are bundled into a Web Archive (WAR) file and added to application EAR files. This section explains how to bundle bonus.html and BonusServlet.class into a WAR file and add it to BonusApp.

    From the Application menus, select New Web Component. A Step 1 of 15 dialog box summarizes the steps you are about to take. After reading it over, click Next.

    In the Step 2 of 15 dialog box, type the path to the directory where the BonusServlet code is located in the top input field. In this example, that directory is ClientCode. When you click Add, a dialog box pops up listing the contents of the ClientCode directory. In this dialog box, choose BonusServlet.class and click OK. When you return to the Step 2 of 15 dialog box, BonusServlet.class appears in the first output field.

    New Web Component Wizard - Step 2 of 15 
      Choose the servlet and JSP bean classpath 
      and their class files
        /export/home/monicap/J2EE/ClientCode
    
    In the Step 2 of 15 dialog box, type the same directory path in the second input field and click Add. When the dialog box pops up, choose bonus.html and click OK. When you return to the Step 2 of 15 dialog box with bonus.html in the second output field, click Next.
      Choose the root directory for your static content 
      and the individual files.
      /export/home/monicap/J2EE/ClientCode
    
    In the Step 3 of 15 dialog box, specify the name and location for the WAR file you are creating, and include a display name and description for the file. The Contents box displays the two files you added to the WAR file in the last step. In this example, the WAR file is stored directly under the J2EE directory. You can ignore the other fields on this dialog box for now because the example, is very simple and does not use them. Click Next when you finish providing the information.
    New Web Component Wizard - Step 3 of 15 
     WAR file:
       /export/home/monicap/J2EE/BonusApp.war 
     Display Name:
       BonusAppWar
     Description:
       This WAR file contains bonus.html 
       and BonusServlet.class
    
    You can click Next and bypass the Step 4 of 15 Environment Entries (java.util.Properties), Step 5 of 15 EJBs Referenced in Code, Step 6 of 15 Resource Factories, Step 7 of 15 Welcome Files, and Step 8 of 15 Authentication Method dialog boxes.

    This simple servlet does not use properties (environment entries), and although it looks up the session Bean (referenced EJBs), it is not necessary to specify it in Step 5 here. You will see in a section below how to specify the session Bean JNDI name so it can be looked up that way instead. Also, in this simple example, the servlet does not look up a database or JavaMail session (resource factories), use welcome files (default pages to greet people coming to your web site), or authenticate the user invoking the servlet.

    On the Step 9 of 15 dialog box, select Describe a servlet (if it is not already selected), and Click Next.

    The Step 10 of 15 dialog box asks you to enter the name of the servlet class (without the class extension), a display name, and a description. You can ignore the Startup and load sequence position setting here because this example uses only one servlet.

    New Web Component Wizard - Step 10 of 15
      Servlet class
        BonusServlet
      Display Name
        BonusServlet 
      Description
        BonusServlet calls the CalcBean session Bean
        to compute a bonus.
    
    Click next on the Step 11 of 15 Initialization Parameters, Step 12 of 15 URL Mappings, and Step 13 of 15 Role Names dialog boxes because the simple servlet does not use initialization parameters (to convey web server information to the servlet), URL mappings (to map requests to servlets), or roles (to group users for security purposes).

    On the Step 14 of 15 dialog box, select Create WAR now and click Next. A message box displays to tell you the WAR file was created in the directory you specified in Step 3 of 15. Click OK. The Step 15 of 15 dialog box shows the XML descriptor that was created for the WAR file. This descriptor is used for deployment. Click Done.

    Click Yes on the Question box that pops up to ask you if you want to add the newly created WAR file to the application. Toggle the Local Applications view to see the BonusApp application and its components. Select the various components and view their information in the Inspecting window.

    In the Content pane, you can see that the WAR file contains an XML file with structural and attribute information on the web application, the bonus.html file, and the BonusServlet class file. The WAR file format is such that all servlet classes go in an entry starting with Web-INF/classes. However, when the WAR is deployed, the BonusServlet class is placed in a Context Root directory under public_html. This placement is the convention for Servlet 2.2 compliant web servers.

    If you want to change the display name or description, put your cursor in the appropriate field in the Inspecting window and change them as you wish. Your edits take effect with you press the Return key.

    Specify JNDI Name and Root Context

    Before you can deploy the BonusApp application and its components, you have to specify the JNDI name BonusServlet uses to look up the CalcBean session Bean, and specify a context root directory where the deployer will put the web components.
    JNDI Name
    To specify the JNDI name, select BonusApp in the Local Applicatons window. The Inspecting window displays tabs at the top, and one of those tabs is JNDI Names. Click it.

    The Inspecting window shows a two-column display with one row. CalcBean is listed in the left column, and in the right column type calcs and press the Return key. That JNDI name is the same JNDI name passed to the BonusServlet.lookup method.

    Context Root
    Click the Web Context tab at the top of the Inspecting window. You will see BonusAppWar in the left column. Type BonusRoot in the right column and press the Return key. That context root is the same name supplied in the bonus.html form for invoking the servlet:
      

    Verify and Deploy the J2EE Application

    Before you deploy the application, it is a good idea to run the verifier. The verifier will pick up errors in the application components such as missing enterprise Bean methods that the compiler does not catch.

    From the Tools menu, choose Verifier. In the dialog that pops up, click OK. The Details window should tell you that all tests passed. That is, if you used the session Bean code provided for this lesson. Close the verifier window because you are now ready to deploy the application.

    From the Tools menu, choose Deploy Application. A Step 1 dialog box pops up that you can ignore by clicking Next.

    In the Step 2 dialog box, make sure the JNDI name shows calcs. If it does not type it in yourself, and press the Return key. Click Next.

    In the Step 3 dialog box, make sure the Context Root name shows BonusRoot If it does not, type it in yourself and press the Return key. Click Next. In the Step 4 dialog box, click Deploy. A dialog box pops up that displays the status of the deployment operation. When it is complete, the three bars on the left will be completely shaded as shown in the figure below. When that happens, click OK.

    Run the J2EE Application

    The web server runs on port 8000 by default. To open the bonus.html page point your browser to http://localhost:8000/BonusRoot/bonus.html, which is where the deployer tool put the HTML file.

    Fill in a social security number and multiplier, and click the Submit button. BonusServlet processes your data and returns an HTML page with the bonus calculation on it.

    Bonus Calculation
    
    Soc Sec: 777777777
    Multiplier: 25
    
    Bonus Amount 2500.0
    

    [TOP]


[ This page was updated: 11-Nov-99 ]

Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-99 Sun Microsystems, Inc.
All Rights Reserved. Legal Terms. Privacy Policy.