| ★ wanayoo — archive 1999 http://developer.java.sun.com/developer/onlineTraining/J2EE/Intro/session.html | Nouvelle recherche | Portail wanayoo |
|
|
|
Training Index
Writing Enterprise Applications
[J2EE TECH CENTER]
[<<BACK]
[CONTENTS]
[NEXT>>] |
|
This next diagram shows how data flows between the browser and the session Bean. The session Bean executes in the J2EE application server.
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.
/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>
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();
}
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");
}
}
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.
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;
}
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;
}
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() { }
}
BonusServlet code is with a script (on Unix) or a
batch file (on Windows).
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
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
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 -verboseIf that does not work, type this from the
J2EE-beta
directory:
Unix: j2sdkee-beta/bin/j2ee -verbose Windows: j2sdkee-beta\bin\j2ee -verboseThe
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.
bin directoy, go to the J2EE-beta
directory (so your live version matches what you see in this
text) and type:
deployertoolIf 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 aServer Applicationswindow and a grayedUninstallbutton next to it. At the end of this lesson after you deploy the application, you will see the application listed in theServer Applicationswindow. You can clickUninstallto uninstall the application, make changes, and redeploy it without having to stop and restart the J2EE application server.
bonus.html and BonusServlet.class files.
Calc.class,
CalcHome.class,
and CalcBean.class.
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.
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/J2EEIn 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/J2EEIn 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.
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/ClientCodeIn 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.classYou 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.
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.
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.
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: