Previous     Contents     Index     Next     
iPlanet Application Server Developer's Guide



Chapter 4   Introducing Enterprise JavaBeans


This chapter describes how Enterprise JavaBeans (EJBs) work in the iPlanet Application Server application programming model. This chapter begins by defining an EJB's role and delivery mechanisms. Next it describes the three EJB types—entity, session and message-driven beans—and gives details on when to use them. Finally, the chapter provides a design overview of an object-oriented iPlanet Application Server application using EJBs to encapsulate business logic.

This chapter contains the following sections:



What Enterprise JavaBeans Do

In an iPlanet Application Server, EJBs are the application workhorses. Servlets act as the application's central dispatchers and handle the presentation logic. EJBs do the bulk of the application's actual data and rules processing, but provide no presentation or visible user interface services. EJBs enable partitioning of business logic, rules, and objects into discrete, modular, and scalable units. Each EJB encapsulates one or more application tasks or objects, including data structures and operation methods. EJBs take parameters and send back return values.

EJBs always work within the context of a container, which serves as a link between the EJBs and the server that hosts them. The iPlanet Application Server software environment provides the EJB container. This container provides all standard container services denoted by the Sun EJB specification and also provides additional services specific to an iPlanet Application Server.

The container handles remote access, security, concurrency, transaction control, and database accesses. Because the actual implementation details are part of the container, and there is a standard prescribed interface between a container and its EJBs, the bean developer is freed from having to know or handle platform-specific implementation details. Instead, the bean developer can create generic, task focused EJBs to be used with any vendor's products that support the EJB standard.



What is an Enterprise JavaBean?



The EJB architecture is component-based for development and deployment of object-oriented, distributed, enterprise applications. An EJB is a single component in an application. Applications written using EJBs are scalable, encapsulate transactions, and permit secure multi-user access. These applications can be written once and then deployed on any server that supports EJBs.

The fundamental EJB characteristics are as follows:

  • Bean creation and management is handled at runtime by the iPlanet Application Server provided container.

  • Client access mediation is handled by the container and the server where the bean is deployed, freeing the bean developer from having to process it.

  • Restricting a bean to use standard container services defined by the EJB specification guarantees that the bean is portable and deployable in any EJB compliant container.

  • Including a bean in, or adding a bean to an application made up of other, separate bean elements—a composite application—does not require source code changes or bean recompiling.

  • A client's bean definition view is controlled entirely by the bean developer. The view is not affected by the container in which the bean runs or the server where the bean is deployed.

  • EJBs can be dynamically reloaded while the iPlanet Application Server is running.

The EJB specification further states that an enterprise bean establishes three contracts: client, component, and JAR file.


Understanding Client Contracts

The client contract determines the communication rules between a client and the EJB container, establishes a uniform application development model that uses EJBs, and guarantees greater bean reuse. The client contract stipulates how an EJB object is identified, how its methods are invoked, and how it is created and destroyed.

The EJB container enables distributed application building using your own components and components from other suppliers. The iPlanet Application Server provides high level transaction, state management, multithreading, and resource pooling wrappers, thereby shielding you from having to know the low-level API details.

An EJB instance is created and managed at runtime by a container class, but the EJB itself can be customized at deployment time by editing its environmental properties. Metadata, such as transaction mode and security attributes, are separate from the bean itself, and are controlled by the container tools at design and deployment. At runtime, a client's bean access is container-controlled by the server where the EJB is deployed.

The EJB container is also responsible for ensuring that a client can invoke the specialized business methods the EJB defines. While a bean developer implements methods inside the bean, the developer must provide a remote interface to the container that tells the container how clients can call the bean's methods.

Finally, the EJB supplies a home interface for the container. The home interface extends the javax.ejb.EJBHome interface defined in the EJB specification. This provides a mechanism for clients to create and destroy EJBs. At its most basic, the home interface defines zero or more create(...) methods for each way to create a bean. In addition, some EJB types, known as entity beans, must also define finder methods for each way used to look up a bean or a collection of beans.


Understanding Component Contracts

The component contract establishes the relationship between an EJB and its container, and is completely transparent to a client. There are several parts to the component contract for any given bean, as follows:

  • Life cycle: For EJB session beans, this includes the javax.ejb.SessionBean and javax.ejb.SessionSynchronization interface implementations. For EJB entity beans, this includes the javax.ejb.EntityBean interface implementation.

  • Session context: A container implements the javax.ejb.SessionContext interface to pass services and information to a session bean instance when the bean instance is created.

  • Entity context: A container implements the javax.ejb.EntityContext interface to pass services and information to an entity bean when the bean instance is created.

  • Environment: A container implements java.util.Properties and makes these properties available to its EJBs.

  • Services information: A container makes its services available to all of its EJBs.

Finally, you can extend the component contract to provide additional services specific to an application.


Understanding JAR File Contracts

The standard format used to package an enterprise bean is the EJB-JAR file. This format is the contract between the bean provider and application assembler, and between the application assembler and the deployer. With the iPlanet Application Server you can create a .jar file containing EJBs using the iPlanet Application Server Deployment Tool. For more information, see the Deployment Tool Online Help.



Note EJB JAR names identified by the first portion of their filenames (without the .jar extensions) must be unique when deploying to the Application Server. Use a Java package-like naming scheme for EAR filenames and EJB names as found in the <ejb-name> portion of the ejb-jar.xml files; this ensures that name collisions do not occur. The benefits of this naming practice apply not only to the iPlanet Application Server, but to other J2EE application servers as well.



The EJB-JAR file must contain the Deployment Descriptor (DD) as well as all class files for the following:

  • The enterprise bean class.

  • The enterprise bean home and remote interface.

  • The primary key class for an entity bean.

In addition, the EJB-JAR file must contain the class files for all classes and interfaces for the enterprise bean class, and the remote and home interfaces to use. For more information on the EJB-JAR file contents, see Chapter 11 "Packaging for Deployment."



Understanding Enterprise Beans



An EJB is an object that represents one of the following:

  • A stateless service

  • A session with a particular client (which automatically maintains state across multiple client-invoked methods)

  • A persistent entity object (possibly shared among multiple clients)

There are three kinds of EJBs: entity, session and message-driven beans. Each bean type is used differently in a server application. The following sections describe the three bean types:


Understanding Session Beans

Session EJBs have the following characteristics:

  • They execute in relation to a single client.

  • Optionally, they handle transaction management according to property settings.

  • Optionally, they update shared data in an underlying database.

  • They are relatively short lived.

  • They are not guaranteed to survive a server crash, unless you use the iPlanet Application Server failover support for stateful session beans.

A session bean implements business rules or logic. All functionality for remote access, security, concurrency, and transactions are provided by the EJB container. A session EJB is a private resource used only by the client that creates it. For example, you might create an EJB to simulate an electronic shopping cart. Each time a user logs in to an application, the application creates the session bean to hold purchases for that user. Once the user logs out or finishes shopping, the session bean is removed.


Understanding Entity Beans

Entity EJBs have the following characteristics:

  • Data representation in the Enterprise Information System (EIS) resource, usually a database.

  • Bean managed transaction demarcation.

  • Container managed transaction demarcation.

  • Shared access for all users.

  • Exists as long as its data is in a database.

  • Transparently survives EJB server crashes.

The server that hosts EJBs and an EJB container provides a scalable runtime environment for concurrently active entity EJBs. Entity EJBs represent persistent data.


Understanding Message Driven Beans

iPlanet Application Server, Enterprise Edition 6.5, provides support for deploying message-driven beans. This implementation is based on the EJB 2.0 specifications, and is for developer use only. The message-driven bean infrastructure in this release has not been tested in a production environment.

Message Driven Beans are similar to Session and Entity Beans in that they support the framework provided by an Enterprise JavaBean. However, message-driven beans are also Java Messaging Service (JMS) listeners and perform tasks based upon the request it receives from a client in the form of JMS Messages.

For more information about JMS, see Appendix A "Using the Java Message Service".

Unlike Session and Entity Beans, message-driven beans process message queues asynchronously, thereby making better use of server resources. The message-driven bean can handle many client requests simultaneously and therefore, does not create message queue bottlenecks.

The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces. Unlike a session or entity bean, a message-driven bean has only a bean class, which implements two standard interfaces.


MDB Properties

A message-driven bean has the following attributes:

  • A message-driven bean's instances retain no data or conversational state for a specific client.

  • All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.

  • A single message-driven bean can process messages from multiple clients.

The instance variables of the message-driven bean instance can contain some state across the handling of client messages--for example, a JMS API connection, an open database connection, or an object reference to an enterprise bean object.

iPlanet Application Server uses the iPlanet Message Queue for Java, 2.0 SP1 as the messaging middleware application that implements the JMS specifications. You must install iMQ for Java, 2.0 SP1 before you can use message-driven beans on iPlanet Application Server.

For more information on deploying message-driven bean, seeChapter 7 "Using Message Driven Beans".

iMQ for Java, 2.0 SP1 is bundled on the iPlanet Application Server installation CD. If you don't have the installation CD, you can download a free, developer edition from http://www.iplanet.com/products/iplanet_message_queue/home_message_queue.html.



EJB Role in an iPlanet Application Server Application



EJBs do the majority of business logic and data processing in an iPlanet Application Server application. They function invisibly behind the scenes to make an application work. Even though EJBs are at the heart of an iPlanet Application Server application, users are seldom aware of EJBs, nor do they ever interact directly with them.

When a user invokes an iPlanet Application Server application servlet from a browser, the servlet invokes one or more EJBs to do the bulk of the application's business logic and data processing. For example, the servlet may load a JavaServer Page (JSP) to the user's browser to request a user name and password, then pass the user input to a session bean to validate the input.



Once a valid user name and password combination is accepted, the servlet might instantiate one or more entity and session beans to execute the application's business logic, and then terminate. The beans themselves might instantiate other entity or session beans to do further business logic and data processing.

For example, suppose a servlet invokes an entity bean that gives a customer service representative access to a parts database. Access to the parts database might mean the ability to browse the database, to queue up items for purchase, to place the customer order (and permanently reduce the number of parts in the database), and to bill the customer. It might also include the ability to reorder parts when stock is low or depleted.

As part of the customer order process, a servlet creates a session bean that represents a shopping cart to keep temporary track of items as a customer orders them. When the order is complete, the shopping cart data is transferred to the order database, the quantity of each item in the inventory database is reduced, and the shopping cart session bean is freed.

As this simplified example illustrates, EJBs are invoked by a servlet to handle most of the application's business logic and data processing. Entity beans are primarily used to handle data access using the Java Database Connectivity (JDBC) API. Session beans provide transient application objects and perform discrete business tasks.

The challenge when creating an application that uses EJBs is determining how to break up an application into servlets, JSPs, session beans, and/or entity beans.



Designing an Object-Oriented Application



Partitioning an iPlanet Application Server application's business logic and data processing into the most effective set of EJBs is the bulk of your job as a developer. There are no hard and fast rules for object-oriented design with EJBs, other than that entity bean instances tend to be long lived, persistent, and shared among clients, while session bean instances tend to be short lived and used only by a single client. Therefore, the following sections are mostly high level iPlanet Application Server specific information to improve application speed, making EJBs modular, shareable, and maintainable.

With all object-oriented development, you must determine what granularity level you need for your business logic and data processing. Granularity level refers to how many pieces you break an application into. A high level of granularity—where you divide an application into many, smaller, more narrowly defined EJBs—creates an application that may promote greater EJB sharing and reuse among different applications at your site. A low level of granularity creates a more monolithic application that usually executes more quickly.



Note Decomposing an application into a moderate to large number of separate EJBs can create a huge application performance degradation and more overhead. EJBs, like JavaBeans, are not simply Java objects. EJBs are higher level entities than Java objects. They are components with remote call interface semantics, security semantics, transaction semantics, and properties.




Planning Guidelines

In general, create an iPlanet Application Server application to balance the need for execution speed with the need for sharing EJBs among applications and clients, and deploying applications across servers:

  • Ask the server administrator to co-locate EJBs with your presentation logic (servlets and JSPs) on the same server to reduce the number of Remote Procedure Calls (RPCs) when the application runs.

  • Create stateless session beans instead of stateful session beans as much as possible. If you must create stateful session beans, have the server administrator turn on sticky load balancing for better performance.

  • Create session EJBs that are small, generic, and narrowly task focused. Ideally, these EJBs encapsulate behavior that is used in many applications.

In addition to these general considerations, decide which parts of an application are candidates for entity and session beans.


Using Session Beans

Session beans are intended to represent transient objects and processes, such as a single database record, a document copy for editing, or specialized business objects for individual clients, such as a shopping cart. These objects are available only to a single client. Because of this, session beans can maintain client-specific session information, called the conversational state. Session beans that maintain the conversational state are called stateful session beans; beans that do not are called stateless session beans.

When a client is done with the session objects, the objects are released. When designing an application, designate each temporary, single client object as a potential session bean. For example, in an online shopping application each shopping cart is a temporary object. The cart lasts only as long as the customer selects items for purchase. Once the customer is done and the order is processed, the cart object is no longer needed and is released.

Like an entity bean, a session bean may access a database through JDBC calls. A session bean can also provide transaction settings. These transaction settings and JDBC calls are referenced by the session bean's container, which is transparent. The container provided with the iPlanet Application Server handles the JDBC calls and result sets.

For a complete discussion of using session beans to define temporary objects and rules for single client access in an iPlanet Application Server application, see Chapter 5 "Using Session EJBs to Manage Business Rules."


Using Entity Beans

Entity beans commonly represent persistent data. This data is maintained directly in a database or accessed through an EIS application as an object. A simple example of an entity bean is one defined to represent a single row in a database table and where each bean instance represents a specific row. A more complex example is an entity bean designed to represent complicated views of joined tables in a database where each bean instance represents the contents of a single shopping cart.

Unlike session beans, entity bean instances are accessed simultaneously by multiple clients. The container is responsible for synchronizing the instance state by transactions in use. This responsibility delegation to the container means that the bean developer does not need to consider concurrent access methods from multiple transactions.

An entity bean's persistence can either be managed by the bean or the container. When an entity bean manages its own persistence, it's called Bean Managed Persistence. When the bean delegates this to the container, it's called Container Managed Persistence (CMP).

  • Bean Managed Persistence: the bean developer implements persistence code (such as JDBC calls) directly in the EJB class methods for bean managed persistence. The possible downside is portability loss, if a proprietary interface is used, and the risk of tying the bean to a specific database.

  • Container Managed Persistence: the container provider uses the Deployment Tool to implement the container persistence. The container transparently manages the persistence state. Therefore, you do not need to implement any data access code in the bean methods. Not only is this method simpler to implement, but it makes the bean fully portable without any ties to a specific database.

For a complete discussion of using entity beans to define persistent objects and business logic in an iPlanet Application Server application, see Chapter 6 "Building Entity EJBs."


Planning for Failover Recovery

Failover recovery is a process in which a bean can reinstantiate itself after a server crash. Both stateless and stateful session beans support failover recovery. The Deployment Tool is used to set the failover properties for session beans; for a description of these settings see the Deployment Tool Online Help. For more information about session bean failover recovery, see Chapter 5 "Using Session EJBs to Manage Business Rules."

Entity beans support failover recovery with the caveat that the reference to the bean is lost after a server crash. To recover an entity bean, you must create a new reference to it with a finder. For more information, see "Using Finder Methods."


Working with Databases

In an iPlanet Application Server, the preferred method for working with databases is through the JDBC API in conjunction with transaction attributes. Use the Java Naming and Directory Interface (JNDI) to obtain a database connection. JNDI provides a standard way for applications to find and access database services independent of JDBC drivers.

For a complete discussion of using entity beans to define persistent objects and business logic in an iPlanet Application Server application, see Chapter 9 "Using JDBC for Database Access."

For a complete description of transaction controls available through session and entity beans, see Chapter 8 "Handling Transactions with EJBs."


Deploying EJBs

Deploy EJBs with the rest of an application using the Deployment Tool. For more information on how to deploy EJBs, see the Deployment Tool Online Help. For information on property settings made by the Deployment Tool and how they affect an application, see Chapter 11 "Packaging for Deployment."


Dynamically Reloading EJBs

EJB reloading in an iPlanet Application Server is done without restarting the server by simply redeploying the EJB. This can also done by replacing the new EJB implementation classfile in the same directory.

iPlanet Application Server notices the new component and reloads it at the next create call on the EJB.



Note
  • EJB reloading applies only to EJB implementation class.

  • The dynamic reloading feature is turned off by default for a production environment. Turn it on when needed.



For more information, see Appendix B "Runtime Considerations".



Using the ejbc Compiler



iPlanet Application Server includes the ejbc utility, which:

  • Checks all EJB classes and interfaces for compliance with the EJB specification

  • Generates stubs and skeletons

Stubs and skeletons are required by the EJB container and must be deployed with the application files. These stubs and skeletons enable remote communication and allow the container to intercept all bean requests.

The ejbc utility generates the following files:


Table 4-1    Files generated by the ejbc utility

File

Description

Required ejbc Option

_Home_Stub.class  

OMG JavaIDL 07-59-99 spec conformant Home Stub class  

-iiop  

_Remote_Stub.class  

OMG JavaIDL 07-59-99 spec conformant Remote Stub class  

-iiop  

_ejb_RmiCorbaBridge_Home_Tie.class  

Home Interface Tie class  

-iiop  

_ejb_RmiCorbaBridge_Remote_Tie.class  

OMG JavaIDL 07-59-99 spec conformant Tie class  

-iiop  

ejb_RmiCorbaBridge_Remote.class  

Remote Interface Bridge  

-iiop  

ejb_RmiCorbaBridge_Home.class  

Home Bridge  

-iiop  

ejb_fac_Implementation.class  

Home Factory  

 

ejb_home_Implementation.class  

Home Skeleton  

 

ejb_kcp_skel_Remote.class  

KCP Remote skeleton  

 

ejb_kcp_skel_Home.class  

KCP Home skeleton  

 

ejb_kcp_stub_Remote.class  

KCP Remote stub  

 

ejb_kcp_stub_Home.class  

KCP Home stub  

 

ejb_skel_Implementation.class  

Remote Skeleton  

 

ejb_stub_Remote.class  

Remote stub  

 

ejb_stub_Home.class  

Home stub  

 

The ejbc syntax for typical use is as follows:

ejbc options Home Remote Implementation

RMIC (Remote Method Invocation Compiler) mode generates only the IIOP stubs and skeleton classes, and it skips the rules checking for EJB spec compliance. The ejbc syntax for RMIC mode is as follows:

ejbc options -rmic Remote

The options can be as follows. If -sl, -sf, or -cmp is not specified, the bean is compiled as a BMP entity bean.


Table 4-2    ejbc options

Option

Description

-sl  

Compiles the bean as a stateless session bean.  

-sf  

Compiles the bean as a stateful session bean.  

-fo  

Compiles a stateful session bean to be Highly Available.  

-cmp  

Compiles the bean as a CMP entity bean.  

-iiop  

Generates additional CORBA classes.  

-gs  

Generates Java source files.  

-d dir  

Specifies the output directory.  

-help  

Displays a syntax summary.  

-rmic  

Generates RMIC code.  

-classpath classpath  

Sets the classpath.  

-cp  

Deprecated; use -classpath instead.  

-javaccp classpath  

Adds a prefix to the javac classpath.  

-debug  

Runs the ejbc utility in debug mode and prints debugging information.  



Using JNDI to Reference an EJB



The JNDI naming scheme for lookups of EJBs is illustrated here with an example (patterned after the HelloWorld sample that ships with the server). The servlet source file, GreeterServlet.java, looks up the home of the bean TheGreeter.



Note The principles illustrated here are also applicable to EJB lookups from one EJB to another.



The JNDI Lookup in the GreeterServlet.java file looks like this:

initContext = new javax.naming.InitialContext();
String JNDIName = "java:comp/env/ejb/greeter";
Object objref = initContext.lookup(JNDIName);
GreeterHome myGreeterHome =
   (GreeterHome)PortableRemoteObject.narrow(objref,
   GreeterHome.class);



Note iPlanet recommends that all references to EJBs be organized in the ejb subcontext of the application component's environment (for example in the java:comp/env/ejb subcontext).



The ejb-ref entry in the web.xml file of the referencing component looks like this:

<ejb-ref>
   <ejb-ref-name>ejb/greeter</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <home>samples.helloworld.ejb.GreeterHome</home>
   <remote>samples.helloworld.ejb.Greeter</remote>
   <ejb-link>TheGreeter</ejb-link>
</ejb-ref>

Two attributes are important in web.xml with respect to JNDI naming:

  • The ejb-ref-name attribute defines the lookup string as used in the source file.

  • The ejb-link attribute connects this reference to the target enterprise bean. This is the name defined in the ejb-name attribute of the ejb-jar.xml file of the target enterprise bean.

According to the J2EE specification, the target bean should be part of an EJB JAR module that is in the same J2EE application.

When the application is deployed, the references are stored in the registry (in LDAP) at the following location:

SOFTWARE\iPlanet\Application Server\6.5\J2EE-Module\module_name\ejb-refs

Figure 4-1 shows the registry entry.

Figure 4-1    EJB reference registry entry



The ejb-ref entry in the ias-web.xml file of the referencing component looks like this:

<ejb-ref>
   <ejb-ref-name>ejb/greeter</ejb-ref-name>
   <jndi-name>ejb/TheGreeter</jndi-name>
</ejb-ref>

In the ejb-ref section of the iPlanet specific deployment descriptor, ias-web.xml, the lookup name (same as the ejb-ref-name attribute in web.xml) is connected to the JNDI name of the target enterprise bean. The JNDI name of a bean is ejb/bean_name. For example, if the bean name (as defined by the ejb-name attribute in the ejb-jar.xml file of the target bean) is TheGreeter, then the JNDI name of the deployed bean is ejb/TheGreeter.

Finally, the ejb-jar.xml file of the target enterprise bean looks like this:

<ejb-jar>
   <enterprise-beans>
   <session>
      <display-name>TheGreeter</display-name>
      <ejb-name>TheGreeter</ejb-name>
      <home>samples.helloworld.ejb.GreeterHome</home>
      <remote>samples.helloworld.ejb.Greeter</remote>
      <ejb-class>samples.helloworld.ejb.GreeterEJB</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Bean</transaction-type>
   </session>
   ...
</ejb-jar>

The deployment descriptor of the target enterprise bean (the ejb-name attribute) is the same as the ejb-link attribute of the web.xml file and the JNDI name (jndi-name in ias-web.xml) of the referencing component. Also, the bean type, home, and remote interfaces should be the same in the deployment descriptors of the referencing component and the target bean.

For more information about the web.xml, ias-web.xml, and ejb-jar.xml files, see Chapter 11 "Packaging for Deployment."

When the EJB is deployed, all bean lookups are in the following section of the registry:

SOFTWARE\iPlanet\Application Server\6.5\EJB-Components

Figure 4-2 shows the registry entry.

Figure 4-2    EJB component registry entry




Previous     Contents     Index     Next     
Copyright © 2002 Sun Microsystems, Inc. All rights reserved.

Last Updated March 06, 2002