Stateless session beans can have data members, butthese are only for things like database connections supplied by the EJB container, or read-only reference data, or for temporary data us
Trang 1System.out.println("The popular Java books:");
for(int i=0;i<bookNodes.getLength();i++) {
Element bNode = (Element) bookNodes.item(i);
NodeList temp = bNode.getElementsByTagName("STARS");
if(temp.getLength()==0)continue; // A book without a star rating
Node starsNode = temp.item(0);
String starCode = starsNode.getFirstChild().getNodeValue();
float stars = Float.parseFloat(starCode);
If the XML document was to be checked for validity, a file with a DTD would have to becreated; and a link to this DTD file would have to be set in the XML document file TheXML file would get a DOCTYPE link:
<!ELEMENT LIST (BOOK)+>
<!ELEMENT BOOK (ISBN, TITLE, AUTHORS, FORMAT?, STARS?, SHIPS?,
LISTPRICE?, OURPRICE, SAVE?, USEDPRICE? )>
<!ATTLIST BOOK rank CDATA #REQUIRED>
<!ELEMENT ISBN (#PCDATA)>
<!ATTLIST ISBN code CDATA #REQUIRED>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT AUTHORS (#PCDATA)>
<!ELEMENT FORMAT (#PCDATA)>
<!ELEMENT STARS (#PCDATA)>
<!ELEMENT SHIPS (#PCDATA)>
Trang 2<!ELEMENT LISTPRICE (#PCDATA)>
<!ELEMENT OURPRICE (#PCDATA)>
<!ELEMENT SAVE (#PCDATA)>
<!ELEMENT USEDPRICE (#PCDATA)>
Exercises
Practical
The servlet/JSP/XML exercises continue use of the Apache Tomcat engine as employed inthe exercise for Chapters 7 and 8 Use the M3Gate phone emulator from http://www.m3gate.com/; you can obtain alternative emulators from companies such as Nokia(see also the explorations exercise below)
The XML parser exercises can be done with the xerces parser downloaded from http://xml.apache.org/xerces2-j/index.html Copy xerces.jar into the directory whereyou are developing an application and then specify a classpath like classpath=.:./xerces.jar
(1) Implement a third version of the JSPs needed in the example web application from the
exercise at the end of Chapter 8 This version is to have a modified Records class with anextra method that returns a java.lang.String that is an XML dump of the data in all theRequestDataobjects in its collection The JSPs are to use XSL stylesheets to generate therequired web pages with the data listings and the forms These XML/XSL-based JSPs aresimple: invoke XSLT processor using an XSL script (request.xsl, review.xsl) applied
to data obtained via the ‘get xml data’ method of the Records bean that is passed fromservlet to JSP
The real code is in the two xsl stylesheet files that you must create
Your WEB-INF directory will need to contains a tld subdirectory with the xsl.tld file,and a lib subdirectory with components like xerces.jar and xsl.jar The JSPs willneed directives like <%@ taglib uri="/xsltaglib" prefix="xsl" %>
(2) Implement a more complete version of the ‘pizza order’ example application that
allows WAP-equipped customers to submit orders for customized pizzas via the webphones
(3) Build an application that combines:
G Static form pages
Trang 3G XSL stylesheets for generating both HTML and WML documents.
The system is to allow students to obtain lecture details for chosen subjects Queriesmay be submitted either via forms displayed on a web browser, or via a form displayed on
a WAP-enabled phone The system will respond with data for the subjects; the WAP-baseddisplay will, naturally, show only a subset of the data shown via a browser
The system should have the following components:
G Query.html, Query.wml
These are static form entry pages for HTTP and WAP browsers The form allows a user toselect a discipline (from among a set of options in a select entry field), and a session ofinterest (again, picking an option – Autumn, Spring, Summer, Annual – from the options
of a select) A discipline is something like Mathematics, IT, Computer Science, Biology, ; details of all subjects in that discipline should be retrieved The form also includes a
‘Style’ parameter (as a hidden field in the HTML form, and as an extra postfield in theWML form); this parameter is included so that the JSP can select the appropriate docu-ment encoding and XSL stylesheet
in the chosen discipline and session The servlet should check whether any subject detailswere retrieved (e.g a request for a Summer session Maths subject might fail to find any) If
no subjects were found, the servlet should use response redirection to an appropriate errorpage (NoData.html or NoData.wml) If the InfoBean found some subjects matching thechosen combination of discipline and session, the servlet will add the bean to the request as
an extra attribute and forward the request to the JSP for final processing
The third table contains lecture times Each row has a subject code, a time string tains day and time), a location string (lecture theater) and duration (hours of lecture).You will need to invent data to populate your tables You need sufficient data so thatthere are subjects defined in at least two disciplines; one discipline has more than one sub-ject in at least spring and autumn sessions, and these subjects have one or more lecturetimes allocated (About 20 rows of data are needed in your three tables.)
Trang 4<!ELEMENT RESULTS (SUBJECT)+>
<!ELEMENT SUBJECT (CODE, LECTURER, TITLE, PHOTO, ABSTRACT, LECTURE+)>
<!ELEMENT CODE (#PCDATA)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT LECTURERE (#PCDATA)>
<!ELEMENT PHOTO (#PCDATA)>
<!ELEMENT ABSTRACT (#PCDATA)>
<!ELEMENT LECTURE (TIME, LOCATION, DURATION)>
<!ELEMENT TIME (#PCDATA)>
<!ELEMENT LOCATION (#PCDATA)>
<!ELEMENT DURATION (#PCDATA)>
G Java Server Page
This will be a simple JSP that extracts the Style parameter from the request and uses this
to set the document type and select a stylesheet It will then use XSL and the chosenstylesheet to format data obtained from the InfoBean that is passed as an attachment in therequest context
G WMLConvert.xsl, HTMLConvert.xsl
These stylesheets contain XSL code for formatting data in the XML document from theInfoBean
The HTML stylesheet will generate a page that starts with a contents section that is a list
of intra-page links to sections for each subject Each subject will have all data shown, withlecture times shown in a table
The WML stylesheet will generate a first card with a list of links to cards generated foreach subject Each subject card will show the subject title and lecture times
The following XML parsing exercises require an XML data file containing a reasonable amount of data (several hundred data items) This data file purportedly contains records
of usage of resources at a web site (with the original data coming from an Apache log file) You can write a Java or Perl program to generate a suitable data file containing invented records (If you did the Perl exercises that created a database of records from Apache log files, you could rework that program to generate a database with the required data, and then have a simple Perl or Java program that dumps the database contents as an XML file.
Trang 5Some databases have an XML output feature that can generate such XML dumps automatically.)
The XML file consists of a resourcelist element with several hundred resource ments Each resource is characterized by a name (supposedly the path name of a resource
ele-on the local web server) and two counts (campus and remote) that record the number of requests for the resource from within the host domain and from sites external to the host domain A resource also has a category attribute that distinguishes text files (.html, txt, pdt), images (.gif, png), CGI programs/scripts, JSPs etc.
The following fragment illustrates the form of this XML document:
Trang 6Separate statistical records are to be prepared for on ‘campus’ and ‘remote’ usage.When all the data have been processed, the program is to produce a report similar to thefollowing:
Accesses to Text data
This program is to produce a report that identifies:
G The text file most frequently used from on campus
G The text file most frequently used from off campus
G a list of all text files that are used significantly more frequently from off campus thanfrom on campus (include files where more than 65 per cent of the total usage is from offcampus); the listed data should show filename and on-campus and off-campus usagecounts
Short answer questions
(1) Explain the different approaches used by SAX and DOM parsers for XML documents (2) Explain the structure of each ‘Element’ defined in the following DTD and the resulting
structure for a valid XML fragment
<!ELEMENT security-constraint (web-resource-collection+,
Trang 7(1) Research and report on the existing services that deliver WWW-related content
through to WAP phones
(2) The phone companies are suffering; their stock prices have slumped because they have
spent too much on the purchase of radio spectrum slots for future generation phone vices They cry out for a killer application that will induce millions of customers to sub-stantially increase their mobile phone usage (and expenditure)
ser-Get some ideas by researching the proposals that have already been made for servicesdelivered via WAP phones, come up with the killer application, and write a draft proposalthat will attract start-up funding for your application
(3) Pick a business domain (finance, real estate, health care etc.) and research and report
on the extent to which there has been agreement for standard XML documents for datainterchange
(4) The original WAP/WML specifications make no provision for anything like ‘cookies’
thus limiting the range of applications to those that don’t require stateful sessions.There are proposals for adding equivalent mechanisms Research these proposals andreport on likely WAP extensions that will help support stateful sessions
(5) Research and write a short report on the different phone emulators that are available
for testing WML applications
(6) Applications of XML include all kinds of mundane things, like defining software
con-figurations, describing program structures, encoding remote procedure calls, senting dumps of database tables and defining EDI formats Get onto the WWW anddiscover and report on some of the more unexpected and esoteric applications of XML
repre-(7) Research and report on the advantages of ‘schemas’ (as compared to older DTDs) (8) Research and report on the merits of the different XML parser implementations for
Java (xerces is not the only parser library)
(9) Many database systems now incorporate mechanisms for dumping the contents of
tables, or the results of queries, as XML documents Research and write a report on theextent of XML support in the database that you use (if it does not have XML support, picksomething like SQLServer or Oracle)
Trang 9Enterprise Java
This chapter provides an introduction to Enterprise Java technologies These technologies(and the somewhat comparable NET technologies from Microsoft, see Appendix C) areaimed at applications that are far more demanding than the simple ‘web site with orderform’-style applications reviewed in earlier chapters These technologies support compo-nent-based approaches to the design, implementation and deployment of enterprise levelapplications; applications that typically involving inter-working of objects in differentprocesses on different machines, and updates of multiple databases The goal is to sim-plify the construction of distributed transactional applications, reducing developmenttimes and costs
Enterprise Java comprises a number of separate but interrelated Java technologies Youare somewhat familiar with four of them: Java Database Connectivity JDBC, JavaServlets, Java Server Pages, and Java-XML Other Enterprise technologies include:
G JavaMail
G Java IDL and related support for CORBA – Common Object Request BrokerArchitecture
G Enterprise JavaBeans (EJB)
G Java Messaging Services
G Java Transactions
G Java API for XML Processing
G Java Naming and Directory Interface (JNDI)
The JavaMail API provides programmers with a convenient interface to the mail vices supported by the operating system It could be used in, for example, an applicationthat relies on email services to acknowledge orders submitted via the web and then to pro-vide updates on the progress of the order
ser-EJB and CORBA are both distributed object technologies These technologies are used
to build multi-tier client server systems A typical three-tier system would have a Javaclient application, a middleware component that would either be a CORBA application or
an EJB application, and a back-end database Web-based clients would typically form part
of a four-tier system The browser-based client would work with a web server that would
Trang 10most likely use servlets This web server would then work with the CORBA or EJBengine; once again, there would be back-end database(s) Programs built using these tech-nologies involve communications among objects instantiated in different processes (it issimilar to, though generally a little more complex than, Java RMI which you may haveencountered previously) Ultimately, client and server objects communicate via messagestransferred over TCP/IP networks A major aim of the distributed object technologies isthe concealment of this network layer A client program (a Java client application, or aservlet in a web server) will make use of instances of proxy (stub) classes that have inter-faces that mimic those of the real server classes as instantiated in the EJB or CORBAengine When an operation is invoked on a proxy, this object packages the request anduses low-level library components to transmit it to the server process There the request isread, analyzed to identify the server object required, and converted into an invocation ofthe appropriate server operation The server-side infrastructure code takes result data,packages them for transmission and sends them back to the client process There thereturned data are picked up by the proxy, allowing it to sustain the illusion that it did thework and is returning a result Invocations on remote objects are synchronous; the clientthread that invokes an operation on a proxy is blocked until the response is received.Java Messaging services support a different, asynchronous model for client–serverrelations among objects Sometimes, it is more convenient for a client to package arequest, and submit this package to a queuing system Server processes will extractrequests from this message queue, perform the work required, and queue responses Atsome later time, a client will retrieve the response to its request The EJB system hasrecently been extended so that it can be integrated with Messaging-style services.With JDBC, you can control the transactional character of operations that use a particulardatabase connection In more complex cases, transactions may involve multiple databases;such situations require more elaborate control mechanisms The Java Transaction API pro-vides a high-level interface to services implemented using Java Transaction Services TheJTS layer is modeled on, and can interoperate with CORBA transaction systems.
The Java API for XML Processing (JAXP) is a second-generation version of Javaclasses for XML and is intended by Sun to become the standard for Java applications Itincorporates both SAX and DOM parsers, and also incorporates support for XSLstylesheet processing
The JNDI naming and directory components provide a uniform interface to many ferent ‘naming services’, so simplifying the tasks of the developer Naming services that areused by programs include DNS; COSNaming (a naming service used to obtain references toCORBA objects); the Lightweight Directory Access Protocol (LDAP), which is a widelyused directory service applied to things such maintaining lists of employees (an employeemight have a name comprising person name, employment unit and department name); andNIS+, a naming service used on groups of Sun Solaris machines that enables the sharing offiles and user accounts across those machines All these services support some form of com-pound name; they vary in the nature of the components in the name and the rules for nameconstruction The JNDI interfaces try to conceal such differences of detail
dif-If you are implementing a medium sized web-based application in Java, you should findthat JDBC, servlets, JSP and a little XML to be quite sufficient You move into the otherareas of Enterprise Java only when attempting something much more ambitious The scale
Trang 11of the endeavor is obviously vast EJBs are the next Enterprise technology with which youmight work The introductory tutorial manual for EJBs has over 450 pages This tutorialmust be supplemented with reference manuals detailing the class interfaces and manualsexplaining the use of necessary support tools Most of the other Enterprise technologiesare of comparable complexity.
This chapter provides a brief introduction to EJB technology The EJB development kit isavailable as a download from Sun (at http://java.sun.com/j2ee/download.html; see alsohttp://java.sun.com/products/) The download package includes archives with the classfiles, interfaces, class documentation, support tools, a tutorial and examples It is intended forSolaris and Windows NT-based operating systems; it may work on Windows 98 and similarsystems, but is not officially supported on these systems Part of the content of this chapter is acommentary on the examples in this EJB tutorial The examples in the tutorial form asequence illustrating various facets of EJB structure and deployment, but really only the last
of the examples (the transactional bank) illustrates an appropriate use of the technology
10.1 EJB background
10.1.1 Smart beans in smarter containers
The Java examples in the last few chapters have illustrated an increasing ‘separation ofconcerns’ A servlet’s task becomes primarily a limited technical one, dealing first withthe receipt of a request, then with delegation of work to ‘beans’ that perform business-ori-ented and database-related tasks, and finally transfer of responsibility for the generation
of the response to a JSP Some beans have the business logic; it is here that you get therules that determine what operations should be performed Other beans are more con-cerned with the transfer of data to and from tables in databases, using database connec-tions to run SQL operations The database connections will be managed by something –maybe the servlet, maybe the beans themselves A Java Server Page becomes primarilyresponsible for the display of the data that are to be shown to the client A JSP may obtainits data directly from beans that it receives from a servlet, or it may use XML helperclasses to format XML data returned by beans
Servlet and JSP both run within a ‘container’ (along with any ‘data beans’ and ‘businessbeans’ that the servlets create) The container handles instantiation of server objects(servlets and JSPs); it also supports mechanisms that help servlets and JSPs collaborate;and it can help the servlets maintain session state An entire servlet–JSP system isdeployed in accordance with instructions in a war file; this file can contain declarativeconstraints that specify security restrictions on the use of different servlet methods, alongwith initialization data for parameters such as database identifiers and passwords.This implementation style can be pursued further The container part can be made moresophisticated For example, maybe the container should become responsible for the data-base connections There would be two possible gains from such an allocation of responsi-bility First, it would lead to more uniform design of different applications developed for acompany All applications would rely on the container for their database connections;rather than the current situation where typically some applications have servlet-managed
Trang 12database connections, while other applications accord this responsibility to beans ondly, allocation of such responsibility to the container should allow for the use of stan-dardized code that applies more sophisticated mechanisms for connection pooling.Additional ‘standard’ code might be incorporated into the container For example, databeans are essentially in-memory representations of rows in database tables that are cre-ated by loading data from the database; their accessor methods provide read access to thedata, while their mutator methods involve database updates A lot of the code for usingsuch data beans is essentially standard; some of this code can be incorporated into the con-tainer system, while other parts of the code might be capable of being created using sys-tems for automatic code generation.
Sec-The ‘declarative deployment’ approach is also open to extension For example, manyapplications involve transactional updates on multiple data beans The code needed tosupport transactions can again be largely standardized If the transactional code can bebuilt into the container, individual business beans would not need to reimplement it.Instead, the business beans could have declarative descriptors attached; these would iden-tify those operations that were transactional in nature, and maybe give further details such
as the required level of transaction isolation
Such more sophisticated containers do exist They are ‘Enterprise JavaBean’ tainers Rather than servlets and JSPs, they hold Enterprise JavaBeans (EJBs) EJBs can
con-be viewed as sophisticated versions of the little data con-beans and business con-beans that areused by servlets and JSPs EJBs are intended to be reusable components that can be incor-porated into many different applications An EJB container uses a deployment descriptorfile in much the same way that a servlet container, such as Tomcat, uses a war file Thedeployment descriptor file for an EJB container specifies the EJBs that it can run, and thedatabases that it uses Each individual EJB specification in this deployment file can con-tain supplementary data on access controls, as in servlets, and now transactional controls
as well
Often, a system will be deployed with a web container that continues to hold servletsand JSPs, and an EJB container that holds the EJBs Code in the servlet running in the webcontainer must invoke operations of beans hosted in the EJB container In simple test con-figurations, a single process may incorporate both containers In more realistic deploy-ments, one process runs the web container (e.g Tomcat); while another process, probably
on a different machine, runs the EJB container The separation of web server and tion server may permit additional security controls; a first firewall can be used to protectthe web server, and an additional firewall can protect the application server Thisincreased protection is sometimes a motivating factor for the choice of EJB style ratherthan simpler servlet-and-bean style implementations If you are using Java applicationclients, rather than web browser clients, then code in the client application must invokeoperations of EJBs held in an EJB container run by some other process, again typicallyrunning on another machine
applica-10.1.2 Distributed objects
Although it is helpful to view EJBs as more sophisticated versions of the little helper beanclasses used with servlets, and to treat an EJB container as a more powerful version of a
Trang 13servlet container like Tomcat, the EJB systems actually originated elsewhere They arereally the product of experience obtained with CORBA systems.
CORBA remains the premier distributed object technology system CORBA’s strengthsinclude its ability to support systems where client and server are implemented in differentlanguages, and its comprehensive set of ‘services’ that extend the basic distributed objectmodel CORBA developments are of particular importance in organizations that have sub-stantial legacy code (existing applications in Cobol, C, C++, Ada etc that still constitutemajor parts of the company’s IT infrastructure) CORBA components can be used to buildobject-style interfaces to such applications New client applications, using Java-basedgraphic interfaces, are enabled to work with these CORBA objects and thus exploit all thecompany’s existing IT systems However, CORBA programming is challenging A lot ofthe code in a CORBA program, particularly code for the server side, has to focus on
‘housekeeping’ – managing the life cycles of the various server objects that are createdand used Particular patterns of object use do frequently reappear in different CORBAapplications, but each time, similar complex code must be used to implement thesepatterns
The EJB approach exploits the regular coding patterns that are found in distributedobject systems An EJB container incorporates much of the same low-level code thatwould exist in a CORBA server (in fact, it may be the same code; some EJB vendors havebuilt their products on top of existing CORBA servers) However, the EJB containerextends the basic network-related code with additional code that supports certaincommon uses of server-side objects For example, server-side programs frequently needdata bean objects – things that represent the information in a row of a relational table ACORBA programmer must wrestle with issues like the need to have a subordinate ‘Por-table Object Adapter’ that implements a suitable ‘servant management’ policy, and mustselect among different policies such as the use of ‘servant activators’, ‘servant locators’ or
a ‘default servant’ The EJB developers finessed all of this Noting that these data beanswere one of the most common uses of objects created on the server, they built in supportfor such objects The EJB term for data beans is ‘Entity beans’ EJB containers takeresponsibility for managing the life cycle of Entity beans An EJB container keeps Entitybeans in memory If memory gets short and an Entity bean appears inactive, the containercan get rid of it and still reinstate it if it is again needed None of this life cycle manage-ment need concern the application programmer, who can instead devote more time toapplication specific issues
Other common patterns in distributed computing involve various forms of ‘sessionobjects’ for clients A client connects to the server and is allocated a session object that ituses to submit requests; these requests may involve operations on many different server-side data objects Sometimes, the requests that can be made to a session object are all inde-pendent; the session object is not changed in anyway, it simply acts as an intermediary.Many different clients can use the same object In other cases, the server-side object storesdata on behalf of the client, so each client must work with a separate instance of the class.Once again, a CORBA programmer implementing such systems must worry about servantretention (‘servant’ is CORBA-speak for a server-side object), servant activation, and soforth The EJB designers again selected the most common patterns of usage and built insupport for ‘Session Beans’ (with stateless and stateful variants) Once again, the EJB
Trang 14container framework code gets the major part of the responsibility for life cyclemanagement.
The ‘factory object’ design pattern frequently appears in distributed computing Theserver hosts a single ‘well-known’ object (its name might be published through somethinglike the rmiregistry for an RMI server, or a COSNaming name server for CORBA) This
object typically has two methods – ‘create a new XX object with identifier ’ and ‘find or reinstantiate the existing XX object with identifier ’; thus, it acts as a ‘factory’ for XX
objects The EJB developers picked on this mechanism as essentially the only onewhereby clients could contact objects in a server, and again provided additional supportcode in the EJB container
EJB is restrictive: you must use factory objects to create and access other objects; youcan have only two kinds of Session bean and these must obey various usage constraints;Entity beans have specified restrictions and requirements Server-side objects in CORBAcan be far more varied and sophisticated, but are harder to program EJB sacrifices versa-tility, but provides more support for the most common uses of distributed objects.Distributed object technologies like Java RMI and CORBA always have support com-ponents These include compilers and code generators, the runtime ‘object request bro-ker’ (ORB) components for client and for server, and naming services that help a clientfind a named server object Java RMI’s rmic is an example of a code generator; rmic takesinformation on a server class and generates the corresponding proxy class that will beused by clients Name servers include Java RMI’s rmiregistry, and CORBA COSNamingname servers An EJB system is similar is similar to these other technologies It is actually
a bit more automated Developers do not explicitly compile client stubs (as they would dofor RMI); instead, the code generation and compilation processes are invoked automati-cally as an EJB program is assembled The EJB container has all the server-side ORBcomponents; clients work with a few objects from javax.rmi and javax.naming packagesalong with application specific stub classes A naming service is built into the EJB con-tainer (this naming service is for the ‘factory’ objects that clients must contact before theycan work with session or entity beans)
For all its automation, an EJB system remains a distributed technology Your codingstyle must change to reflect this When you implement a servlet with a few helper beans,you are thinking about a single application built from a few classes that you largely definefor yourself When you develop with EJB, you have two applications – client and server,and often two separate development groups Development of the EJB-based server appli-cation involves designing session beans and entity beans that are based on fairly complexclasses defined in the EJB framework, and writing the code for a few of their methodswhile leaving others to an automatic code generation system The client part may be aservlet, or a separate Java application It has to contain code for establishing network con-nections, creating proxy objects and invoking operations via proxies
Your code changes in other ways as well For example, if you use a simple data bean torepresent a ‘customer’ in a servlet, you will probably implement fine-grained accessorand mutator methods such as get/set-Name, get/set-Address, get/set-CustomerID, and soforth Since the servlet and data bean would both be in the same address space, these areall simple method calls In an EJB implementation, your client (servlet or application)would have a ‘Customer Proxy’ object while the actual Customer Entity Bean would exist
Trang 15in the separate address space of the EJB container Each method invocation on the tomer involves network communications, and a quite substantial amount of work by theEJB container Fine-grained access to individual data elements becomes inappropriatebecause of these overheads Instead, you must implement a much coarser-grained inter-face, using methods such as ‘get data’ and ‘set data’ in your customer class Thesemethods would involve the transfer of an instance of a subsidiary data struct (a simpleclass with public data members for all the different data fields in a customer object).You must design your classes in accord with coding conventions for the EJB frame-work This naturally includes provision of effective methods for abstract functions inher-ited from framework base classes In addition, there are many naming conventions thatmust be complied with; a lot of the support code gets generated automatically and thecode-generators depend on your following the naming conventions.
Cus-Finally, there are some unusual aspects to the way that server interfaces are defined inEJB Typically, as in RMI and CORBA, a server ‘interface’ is defined; this lists the publicmethods of the server class giving details of return and argument types and so forth Aserver class will implement this interface, as will the automatically generated client proxy(stub) class Such inheritable interfaces are not used in EJB The creators of the EJBsystem chose instead to rely rather heavily on Java reflection With Java reflection, theruntime system builds Method objects that have data elements that identify the object that
is to perform the work, the member function of that object that is to be used, and the ment data Extensive runtime checks can be performed to verify that correct versions arebeing used and that all data are of appropriate types A side effect of this use of reflection
argu-is the oddity in the way that the interfaces are defined Typically, you declare the classesfor the client and for the actual implementation quite separately The client class declara-tions are used in the system that auto-generates client proxy classes (and some helperclasses used in the server process) Class declarations for the client classes and actualimplementation class must of course match with respect to the defined public methods ofthe server (because otherwise the system will not be able to create appropriate Methodobjects)
10.2 EJB basics
10.2.1 Servers, containers and beans
An EJB server will run as a process on your server machine It will host various ers’ Containers can be web containers (for servlets), or EJB containers that hold enter-prise beans Larger scale applications typically involve multiple EJB servers with one ormore hosting web containers, and several others holding EJB containers The beans used
‘contain-in a s‘contain-ingle application may exist ‘contain-in different EJB conta‘contain-iners Communications betweenclient proxies and beans, and inter-communications among beans, normally involve net-work message traffic; a call from a session bean to an entity bean will go down through anelaborate protocol stack to the TCP/IP level, and then come back up through the same pro-tocol stack The EJB-2 specifications allow for some optimizations of communicationsamong beans that are by design going to be instantiated in the same container
Trang 16The current version of Enterprise Java defines three kinds of Enterprise Bean:
G Session beans – used to perform tasks for clients
G Entity beans – represent a ‘business entity’, most often a block of data taken from a row
A stateless session bean will offer one or more procedural-style services A good use of
such a bean would be to support database queries, where the various queries involve taskslike performing joins on database tables, or the retrieval/update of related data taken frommore than one database Such a session bean will return any results as records (instances
of some simple ‘struct’ like class) held in a Java collection object A client will establishcontact with such a session bean, submit a request with parameters that identify therecords that are to be retrieved, and receive the results A stateless session bean will forgetall about its current client on completion of an invoked method (You can make an analogybetween a stateless session bean and a HTTP server.) Typically, an EJB container willcreate a few instances of each stateless session bean class when it starts, and have theseready to receive client requests (An EJB server is multi-threaded, but it will not allowbeans to be used by more than one thread simultaneously; hence the need to have multipleinstances of a stateless bean.) All stateless session beans are identical; a client that sub-mits several successive requests may have each request handled by a different statelesssession bean (you could make another analogy between a pool of stateless session beansand a pool of Apache tribesmen) Stateless session beans can have data members, butthese are only for things like database connections supplied by the EJB container, or read-only reference data, or for temporary data used while processing an individual request
A stateful session bean performs a sequence of tasks on behalf of a specific client It has
to be created with an identity (e.g the name of the client) Operations on a stateful beanwill return results to the client, and may also change instance variables in the bean itself.Subsequent operations may combine parameter data with data from these instance vari-ables (You can make an analogy between a stateful session bean and an ftp server Eachclient who uses ftp gets a separate process that holds data, such as the client’s login iden-tity, the current working directly, and the transfer mode for files ‘Change directory’ oper-ations define the context for subsequent operations like directory listings and transfer
Trang 17requests.) A popular example use of a stateful session bean is a web ‘Shopping Cart’; such
a bean could have a Vector holding records with item-identifier and quantity members foreach item picked by the client The state data members in a bean are application specific,but all must be instances of java.io.Serializable types or simple built in types (e.g.String, int, int[], Integer, ) A busy EJB server may have to transfer little usedstateful session beans to secondary file storage; a bean that has been removed frommemory gets recreated when its client next makes contact
Entity beans represent persistent data In principle, an entity bean can represent datathat are stored in a file, in an object database, in a hierarchical database, or in a relationaldatabase; overwhelmingly, they are used with relational databases Each bean has an iden-tity element – equivalent to a primary key for a database (Often, this primary key is aninstance of java.lang.String or java.lang.Long classes, but you can define a more spe-cialized primary key class Commercial Enterprise Java development environments incor-porate various ‘wizards’ that help manage the definition and use of such auxiliaryclasses.)
There are two types of entity bean: beans that manage their own transfers to/from sistent storage (Bean Managed Persistence – BMP), and beans that rely on the container tomanage transfers (Container Managed Persistence – CMP) In the case of BMP beans, thedeveloper writes code that obtains a JDBC database connection from the container anduses this to perform SQL operations; the bean class includes declarations for the persis-tent data members With CMP beans, most of the database access code is generated auto-matically; the developer supplies a declarative bean descriptor that identifies the requiredpersistent data elements and, in some cases, must also provide some database operationstatements in an EJB-specific dialect of SQL (these statements are also stored in thebean’s declarative descriptor) A programmer-defined CMP bean class is actuallyabstract; the system defines a concrete subclass A CMP bean class does not define datamembers equivalent to its declared persistent data members; instead it has get/set accessfunctions (virtual data members) The automatic code generation system creates a con-crete subclass with the data members and transfer functions that use a databaseconnection to run SQL operations
per-An entity bean must be created the first time it is ever used; creation of the bean ently involves creation of an entry in the database This entry is associated with the bean’sidentity – primary key Subsequently, an entity bean is ‘found’; it is recreated from data inthe database A ‘remove’ operation on a bean must also entail deletion of the databaserecord
inher-A container may recycle the entity beans that it actually creates in memory; recyclablebeans reduce the work that must be done by the storage manager An entity bean has a datamember for its primary key; setting this data member establishes the identity of the bean.When the primary key member has been set, the bean can be told to reload its other datamembers Typically, a container will pre-allocate a number of entity beans from eachentity class that it manages; these pre-allocated beans don’t have any initial identity –their keys are unset When a specific bean is needed, a pooled bean is used and given anidentity If a client discards a bean, the container can make sure that the database copy isupdated, and then return the bean to its pre-allocated pool
Trang 1810.2.2 The life of a bean
The container manages the life cycle of all beans Thus, for a stateful session bean, thecontainer will have to create a bean initialized with a client-supplied identity, allow theclient to use the bean, possibly transfer the bean to secondary storage (‘passivate’ thebean), activate (restore) a saved bean, and finally remove the bean For an entity bean, thecontainer must take a pooled bean, give it an identity, and get it to reload its other data; atvarious subsequent times, the container must ensure that bean and database versions arekept consistent
The life cycle management code is standard and incorporated into the container, but lifecycle operations do impinge on application-specific code For example, a stateful sessionbean may have acquired a database connection; this connection is not going to be of muchuse if the bean has got itself transferred to secondary storage A session bean shouldrelease any such connection before it is ‘passivated’ and reacquire a new connection whensubsequently activated Such application-specific needs are handled through ‘hook func-tions’ These ‘hook’ member functions are defined as abstract life cycle-related functions
in the base classes such as javax.ejb.SessionBean and javax.ejb.EntityBean Thereare several such functions, for there are many places where it might be necessary to per-form some application-specific processing before or after the container invokes one of thelife cycle methods All these functions must be given definitions in the bean classes,though very often they are empty definitions (e.g void ejbPassivate() { })
10.2.3 Classes and interfaces
When you define an Enterprise bean, you have to define three classes and interfaces Thefirst class is the real bean class itself; this class will be a subclass of javax.ejb.SessionBean or javax.ejb.EntityBean The second interface, which extendsjavax.ejb.EJBObject (which itself extends java.rmi.Remote), is the remote interfacefor the service This must define public functions with signatures identical to the applica-tion-specific functions defined for the enterprise bean The EJB system will generate aconcrete class that implements this remote interface This class is the proxy class that isactually instantiated in a client
The third interface that you must define is the interface for the ‘factory’ that is used tofind or to create enterprise beans on behalf of the client The EJB system generates morethan one class implementing this interface; there is the real factory class used in the EJBcontainer, and a proxy class that allows the client to communicate with the factory.Although the term ‘factory’ has been widely used for years, the EJB developers picked adifferent name for their interface In EJB terms, this is the ‘Home’ interface; it extendsjavax.ejb.EJBHome
A Home interface for a session bean will be simple, involving just one or more ‘create’methods (there are a few other methods declared in the parent EJBHome class, e.g remove)
A stateless session bean requires only a single, no-argument ‘create’ method Stateful sion beans need create methods with arguments that supply an identity and, possibly,other initial state data The corresponding enterprise bean must define matching functionsthat can be used to pass these initializing data to the bean; these must be named
ses-‘ejbCreate’ and have argument lists that match the create functions in the Home interface
Trang 19The Home interfaces for Entity beans are more complex Usually they will define ate’ methods, though occasionally this is not necessary (it is possible that entries in thedatabase are created only by existing legacy applications) In addition to any ‘create’methods, these Entity bean Home interfaces also define ‘find’ methods One obviousmethod is ‘find by primary key’; this is used to recreate an entity bean whose key isknown For both ‘create’ and ‘find by primary key’ methods, a Home interface returns areference to an instance of the application specific subclass of EJBObject.
‘cre-However, the ‘finder’ mechanism is more general than this As in all database-relatedwork, it is often necessary to obtain collections of all records that satisfy constraints onthe values of data members Such extra ‘find’ methods are commonly included in theHome interfaces for entity beans and implemented in the Entity bean class itself (the
Entity bean class must define an ejbFindXX method for each findXX method defined in the
Home interface) For example, with a ‘Customer’ entity bean, as well as the standardfindByPrimaryKey(String customerID) method, you might want a method likefindByCustomerName(String Name); this would retrieve data on all customers whosenames matched the given name string Such methods naturally return collections; they arecollections of EJBObjects (i.e client stub objects) (Actually, it is a bit more complex thanthat The implementation of an ejbFind method in the Entity bean class will returneither a primary key object or a collection of primary key objects The container thenchanges this into a remote object reference, or collection of remote object references, andreturns these data to the client Since the system is based on Java RMI, the support code inthe server returns these references packaged in serialized instances of the client-side stubobjects.)
Entity beans do have to have associated ‘remote’ and ‘home’ interfaces (a bean can only
be contacted via a remote proxy created by a factory object that implements the ‘home’interface) This allows client code (in a servlet or a Java application) to obtain a reference
to an entity bean, and then use this to invoke operations on the database through that bean.Such usage is dubious It results in client code incorporating the business rules that deter-mine permitted operations on databases and so forth Generally, it is better for such rules
to be implemented via code in reusable session beans A client application or servletworks with a session bean (in a client–server relationship); the session bean acts as anintermediary, working with the entity beans (again in a client–server relationship, with thesession bean as client and the entity beans as servers) The session bean must still utilizethe ‘home’ interface of the entity bean class to obtain proxies for the entity beans that itneeds This arrangement allows session and entity beans to run in different containers.However, there are obviously significant costs in using this general mechanism when ses-sion and entity beans are actually instantiated in the same container The EJB Version 2implementation defines the classes javax.ejb.LocalObject and javax.ejb.LocalHome;when you plan for objects that are always going to be created in the same container, youcan use these classes as the base classes instead of EJBObject and EJBHome Apart fromthis use of different base classes, your program structure does not need to change much
Of course, the ‘proxy’ classes created with these local interfaces are normal Java classesand their method calls are normal Java calls, thereby avoiding the network-related over-heads of remote interfaces (You do need to remember that there are changes to how argu-ments are passed Client (session bean) and server (entity bean) parts now work with the
Trang 20same parameter objects, instead of the server getting a separate copy The server maychange these argument objects and any such changes will affect the client This does nothappen with remote interfaces.)
10.2.4 EJB clients and EJB deployment
When you have implemented your Enterprise bean classes, and created the associatedremote and home interfaces for each class, you must still write your client code Simpleclient applications resemble clients for RMI systems They start with a standard sequence
of code used to establish contact with the server (in the case of a servlet client, this wouldbest be done in the servlet’s init method) Where an RMI client will typically be trying tocreate a proxy for some object identified in the rmiregistry, an EJB client will be trying toget a proxy for a Home object in the EJB container If the connection attempt is successful,the client will then use this initial Home proxy object to submit a ‘create’ or ‘find’ requestfor the actual session or entity bean with which it wishes to work This operation willagain result in a proxy object that the client may then use As in RMI programs, the rest ofthe code seems straightforward; the client uses the proxy as if it were any other localobject, invoking methods and receiving results The code must arrange to catchRemoteExceptions, and, as with RMI, all arguments used in method invocations must beserializable with the server working with a copy of the data passed
Finally, you must assemble and deploy your system This step is a little bit like the cesses of writing a web.xml deployment file, and then building a war file for a completedservlet/JSP application; though inevitably it is more complex
pro-Sun’s view of the future has development teams that include individuals with specializedskills such as ‘web component creator’, ‘enterprise bean author’, ‘client applicationauthor’, ‘application assembler’ and ‘application deployer/administrator’ You have someexperience with the role of ‘web component creator’, having created web applications withstatic HTML files, JSPs, web.xml deployment files and servlets Apart from writing thecode for the enterprise beans, an ‘enterprise bean author’ must also compose a deploymentXML file This file, ejb-jar.xml, is considerably more complex than the web.xml files and
is never composed by hand; instead, the developer will use some GUI-based ‘wizard’ thatsteps through the creation process (Sun’s kit includes the deploytool program that incorpo-rates an Enterprise Bean Wizard) This wizard allows the developer to select the class filesthat make up a bean (remote and home interfaces, and the enterprise bean itself), and thenspecify deployment details such as whether the bean is a session bean or an entity bean.The role of ‘client application author’ would probably suit someone with prior experi-ence with Java RMI; the general programming style is similar The ‘application assem-bler’ takes jar files with the enterprise bean components and client applicationcomponents, and war files with servlet/JSP client applications, and assembles these into
an ‘Enterprise Archive’ (.ear file) This archive again incorporates a fairly complexdeployment XML file that is created with the help of a wizard tool Among other data, thisdeployment file contains name mappings that relate the ‘server names’ used in clients(servlet/application) to the enterprise bean that provides the services Finally, the ‘appli-cation deployer/administrator’ is responsible for running the EJB server (this is the j2eeprogram in Sun’s kit), and for adding ear files to the server’s repertoire
Trang 2110.3 Session bean examples
Sun’s kit includes tutorial examples illustrating stateless and stateful session beans Theseexamples are intended only to illustrate the structure and use of such beans; neitherexample represents an appropriate use of EJB technology
10.3.1 Stateless server
The first example is a stateless session bean that handles currency conversion (The mostappropriate technology for such an application would probably be a little PHP scriptaccessing a database table with current conversion rates.) For simplicity, the example con-verter has just two methods implementing specific conversions (dollars to yen, yen toeuro) using fictitious exchange rates defined as constants The Converter Bean examplecomprises:
public interface Converter extends EJBObject {
public double dollarToYen(double dollars) throws RemoteException;
public double yenToEuro(double yen) throws RemoteException;
}
public interface ConverterHome extends EJBHome {
Converter create() throws RemoteException, CreateException;
}
They are both defining java.rmi.Remote interfaces (EJB is based on Java RMI, thoughwith a wire protocol based on CORBA’s IIOP – Internet Inter-ORB Protocol) Conse-quently, every method may throw java.rmi.RemoteExceptions It is standard for the cre-ation functions for all enterprise beans to throw javax.ejb.CreateExceptions While it
Trang 22is unlikely that an attempt to create a session bean would fail, you would certainly get acreate exception if you attempted to create an entity bean with an identifier identical tothat of an existing bean (leading to a non-unique primary key in the corresponding data-base table).
The enterprise bean is:
public class ConverterBean implements SessionBean {
// Constructor and life-cycle methods
// Application specific server methods, signatures
// to match methods in "remote" interface
}
Session beans are required to have a no argument constructor (publicConverterBean() {}) and must provide effective implementations for the life cyclemethods declared in the SessionBean class It is common for most or all these methods toget null definitions; they are after all just hook functions, included to allow for specialcases where some particular action is needed before or after the container forces somemajor life cycle change on the bean
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
There is one more inherited method that must be defined, setSessionContext(SessionContext sc) The container calls setSessionContext just after it creates thebean, and before it calls the ejbCreate initialization function The argument is a reference
to an object that can supply information such as details of a client’s identity (if using somesecurity controls) or the state of any current transaction A bean can have aSessionContext instance member that is used to save a reference to this context; thesetSessionContextmethod sets this member for later use Like most session beans, thisbean does not have any need to access the context and so this method is empty:
public void setSessionContext(SessionContext sc) {}
The application-specific member functions are trivial, e.g.:
public double dollarToYen(double dollars) { return dollars * 121.6000; }The client application program is:
public class ConverterClient {
public static void main(String[] args) {
Trang 23// Report any exceptions
}}
}
EJB clients use JNDI naming services to contact the name server that is built into a tainer An InitialContext object is created and then used to lookup a named resource:Context initial = new InitialContext();
con-Object objref = initial.lookup("java:comp/env/ejb/SimpleConverter");The naming service in the server has a structure equivalent to a file hierarchy, with an ‘en-vironment’ section that has subsections for EJBs, and for database sources etc The ‘JNDIname’ used by the client application will correspond to an entry in the ejb section ThisSimpleConverter entry is created when the application is deployed and the namemapping data are in one of the XML deployment files This lookup step is generally similar
to that in an RMI program (e.g CalculatorFactory theWorks = (CalculatorFactory)Naming.lookup("rmi://cs.bigcampus.edu:13456/Calc") The RMI Naming.lookupoperation uses a URL that identifies the host machine and port used by the requiredrmiregistry program; and then has a simple object name The JNDI-based version definesthe source machine and port for the naming server from system parameters (taken from aproperties file, or as command line environment variables, or set in code) In this example, it
is relying on defaults with the EJB server running on the local host using standard ports.The Object reference returned from the lookup operation must be cast to the appro-priate type Ordinary Java casts cannot be used here; instead, a ‘narrowing’ operation isdone, as in CORBA:
ConverterHome home = (ConverterHome)
PortableRemoteObject.narrow(objref, ConverterHome.class);
(This narrowing operation performs further runtime checks that verify that objects areindeed of the appropriate type.)
Trang 24Once a reference to the Home (factory) object has been obtained, it can be used to create
a currency converter object:
Converter currencyConverter = home.create();
Finally, the conversion operations may be performed using this converter:
double amount = currencyConverter.dollarToYen(100.00);
System.out.println(String.valueOf(amount));
The web-based client uses a JSP; this JSP is run in a web container hosted in the j2eeengine alongside the EJB container The JSP displays a form, and possibly some outputtext showing the results for any previous operation The form allows the user to enter theamount of money that is to be converted Scriptlet code is used for the interactions with theEJB system The JSP starts with a page directive that imports the various Java packagesrequired, then has a declaration section for some of the scriptlet code, and finally someHTML tags, content text and scriptlet expressions:
<%@ page import="Converter,ConverterHome,javax.ejb.*, javax.naming.*,
javax.rmi.PortableRemoteObject, java.rmi.RemoteException" %>
<%!
// Declare instances variables and member functions for
// servlet generated from this page
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
String amount = request.getParameter("amount");
if ( amount != null && amount.length() > 0 ) {
Double d = new Double (amount);
Trang 25<%= amount %> Yen are <%= converter.yenToEuro(d.doubleValue()) %> Euro.
<%
}
%>
</body></html>
The scriptlet code includes a large declaration section with an instance variable to hold
a reference to the converter and a jspInit method that establishes the connection Thecode for this jspInit method is similar to the code in the application client (Sun’s devel-opers chose to have the JSP and the application client use different names for the service,and use this feature to illustrate further use of the JNDI naming services) The declarativesection of the scriptlet code is:
private Converter converter = null;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
Object objRef = ic.lookup("java:comp/env/ejb/TheConverter");
ConverterHome home = (ConverterHome)PortableRemoteObject.narrow(objRef, ConverterHome.class);
public void jspDestroy() { converter = null; }
Sun’s tutorial contains several pages of detailed instructions that explain the stepsneeded to assemble and deploy this EJB application and its clients The archive files andthe XML deployment files that get created are not intended for human consumption How-ever, their structure and content for this simple example are reasonably revealing and mayhelp you obtain a better understanding of the deployment process (The structures for thearchive files, and the forms for the XML files, are largely standardized An applicationbuilt for one EJB implementation is supposed to be easily transferred to another How-ever, a particular EJB system may create the odd specialized XML file with deploymentdata that are specific to its EJB server.)
The ‘Enterprise Archive’ (.ear) file created for this example contains the followingfiles and directories:
Trang 26One jarhave to be installed on a client machine that runs the application client; theother jar file contains resources used by the EJB server that will host this bean The warfile contains the resources that are needed by the web server that hosts servlets and JSPs.The application.xml file describes the module structure; in this case, there are threemodules (server, client and web client):
The main ejb-jar-ic.jar file contains the class files for the ConverterBean and itsassociated home and remote interfaces, and the ejb-jar.xml deployment file It is thisejb-jar.xmlfile that contains all the information that the container needs to operate with
a particular enterprise bean The file for this example is:
Trang 27refer-10.3.2 Stateful server
Sun’s second session bean example is a variation on the ubiquitous shopping cart for abookstore site (Again, it isn’t intended to illustrate a good use of EJB, merely to illustratethe form of the classes Sun has a better shopping cart in the ‘Duke’s bookstore’ servletexample.) The only features of interest are the various ‘create’ methods in the home inter-faces (and corresponding ‘ejbCreate’ methods in the session bean class), the return datatypes for one of the cart’s methods (it illustrates a bean returning collections of data, inthis case a collection of Strings), the state data (identifier data for the bean, and a Vector
to store books), and some minor details of the XML deployment file (like the tag fying it as a stateful bean)
identi-The home and remote interfaces for the cart are:
public interface CartHome extends EJBHome {
Cart create(String person)
throws RemoteException, CreateException;
Cart create(String person, String id)
throws RemoteException, CreateException;
}
public interface Cart extends EJBObject {
public void addBook(String title) throws RemoteException;
public void removeBook(String title)
throws BookException, RemoteException;
public Vector getContents() throws RemoteException;
Trang 28public class CartBean implements SessionBean {
String customerName;
String customerId;
Vector contents;
// ejbCreate (initialize) methods
public void ejbCreate(String person) throws CreateException {
if (person == null) {
throw new CreateException("Null person not allowed.");
}else customerName = person;
}else customerName = person;
// Code to check validity of id argument
contents = new Vector();
public Vector getContents() { return contents; }
// Life cycle methods
}
The life cycle methods would again all be empty because this bean does not requireany special actions on life cycle changes You can put tracers in life cycle methods (orany methods); these can help debugging It is a bit like putting tracers in your servlets;there the messages appeared in the window for the terminal session controlling theTomcat server (or were sent to a log file) With EJBs, trace messages will appear in awindow associated with the EJB server
Trang 29public void ejbPassivate() {
System.out.println("Pasivating cart for " + customerName);
Trang 3010.4 An Entity bean
Bank account examples must be the ‘Hello World’ programs for distributed systems; theyappear with every introductory presentation of technologies like RMI, CORBA, EJB andSOAP Sun’s tutorial keeps in fashion, using a bank account as its first illustration of anentity bean
These beans represent rows from a database table defined as follows:
CREATE TABLE savingsaccount
sup-public interface SavingsAccountHome extends EJBHome {
public SavingsAccount create(
String id, String firstName,String lastName,
double balance)throws RemoteException, CreateException;
public SavingsAccount findByPrimaryKey(String id)
throws FinderException, RemoteException;
public Collection findByLastName(String lastName)
Trang 31throws FinderException, RemoteException;
public Collection findInRange(double low, double high)
throws FinderException, RemoteException;
}
The findByPrimaryKey method recreates a bean that represents a specified account; theother two ‘find’ methods return collections (accounts where a surname matches, accountswith a balance in a specified range) These ‘find’ method all have the potential of throwingFinderExceptions(e.g an invalid account identifier supplied to findByPrimaryKey)
A client can deposit and withdraw funds, and review other properties of an account;these operations are defined through the remote interface:
public interface SavingsAccount extends EJBObject {
public void debit(double amount)
throws InsufficientBalanceException, RemoteException;
public void credit(double amount)
sev-The demonstration client application that Sun provides is pretty much as you wouldexpect JNDI naming services are used to establish a connection, via a proxy, to a Homeimplementation object in the server; the local Home proxy is then used to perform actionssuch as account creation, retrieval of an existing account identified by its identifier(findByPrimaryKey) and retrieval of collections of accounts (findByLastName) Theaccount objects (proxies) obtained via these operations are then used to invoke operations
on the entity beans and thence on rows in the underlying database
public static void main(String[] args) {
try {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/
SimpleSavingsAccount");
SavingsAccountHome home = (SavingsAccountHome)PortableRemoteObject.narrow(objref,
SavingsAccountHome.class);