Day 1. Understanding EJB Architecture



Developing enterprise applications has become a daunting task. Enterprise applications are complex, used by many users, developed by multiple teams, and deployed on heterogeneous systems that might span multiple environments. In addition, enterprise applications have to be distributed, secure, transactional, reliable, scalable, flexible, expandable, reusable, and manageable. Moreover, enterprise applications must be integrated with existing systems, and leveraged against the existing infrastructure.

Enterprise JavaBeans (EJB) is a component-based architecture for developing, deploying, and managing reliable enterprise applications in production environments. EJB architecture is at the heart of the Java 2 platform, Enterprise Edition (J2EE). With the growth of the Web and the Internet, more and more enterprise applications are now Web based, including both intranet and extranet applications. Together, the J2EE and EJB architectures provide superior support for Web-based enterprise applications.

The following is a summary of today’s target in exploring both the EJB technology and J2EE architecture. You’ll learn

  • What EJB is, and its benefits in simplifying the writing of enterprise applications

  • How EJB is different from ordinary JavaBeans

  • About the big picture of the J2EE, and where EJB fits into it

  • What flavors of beans are available, and the characteristics of each

  • The importance of the EJB container, and the available common services provided to your beans

  • More about the roles and responsibilities in developing and deploying J2EE applications—who does what

    The Challenges of Developing Enterprise Applications

    Enterprise applications are facing many challenges, such as portability, reusability, interoperability, and application integration. Since the inception of Java in 1995 as a simple object-oriented and portable language, its main focus was on the development of portable client-side applications. The challenges of developing portable Java enterprise applications remain due to the lack of server-side application development framework and tools. By server-side computing, we imply the design of small, location-transparent components that work together to fulfill enterprise service requirements. In many cases, these lightweight components can work as both client and server.

    Enterprise computing is rapidly changing in both hardware and software. New applications are required to meet with the emerging user demands, and are still required to interface with existing applications. It’s not practical to throw out the huge investment in applications written in older-generation languages that already work to maintain data in legacy systems. This dictates a need to integrate new applications with the existing systems. Today, server-side software offers the corporate world many opportunities to rethink its enterprise-wide computing infrastructure. With the acceptance and growth of Java in recent years, software portability, reuse, and application integration have become important and accepted for many client applications spread throughout the enterprise.

    Enterprise applications are complex, and in many cases require the development of several teams, which might span multiple domains. Today’s applications are required to have faster time to market to compete and to fulfill user demands. Another challenge facing the enterprise is interoperability with other environments, which might be heterogeneous in hardware, software, or network architectures.

    In facing such challenges, enterprise application architectures have undergone an extensive evolution. The first generation of enterprise applications was centralized mainframe applications. In the late 1980s and early 1990s, most new enterprise applications followed a two-tier architecture approach (also known as the client/server architecture). Later, the enterprise architecture evolved to a three-tier, and then to a Web-based architecture.

    One of the solutions for these challenges is the J2EE technology, which was developed by Sun Microsystems. The following sections describe the J2EE architecture and, as a major participant, the EJB technology of developing component-based enterprise applications.

    What’s an EJB?

    Let’s first understand the meaning of component and server component model, and then examine the meaning of EJB. A component is a piece of code that implements well-defined interfaces. Typically, it lives in a runtime environment and takes advantage of the services offered by the environment. For the component to live in a runtime environment, it must follow the rules of the runtime environment. This ensures the proper functioning of the runtime environment and the portability and scalability of the component. A component is not a complete application. An application consists of multiple components working together.

    Generally, developing server-side objects is more difficult than writing graphical user interface (GUI) or client components. This is because in addition to writing business application logic, the developers must also take care of system-level issues such as multithreading, access to databases, efficient management of resources, transactions, security, access to legacy systems, and so on. A server component model or architecture provides support for server-side components. This simplifies the development of server-side components and allows developers to focus on developing business application logic.

    An enterprise bean is a server-side component that implements the business logic of an enterprise application and adheres to the rules of the Enterprise JavaBean architecture. Enterprise beans live in an EJB container—a runtime environment within a J2EE server. The EJB container provides multiple services to support the enterprise beans.


    The Enterprise JavaBeans specification states, “The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based distributed business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification. The Enterprise JavaBeans architecture will make it easy to write applications: Application developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs.” The entire 500+ pages of the specification, meant for application server vendors to digest and implement, can be accessed at


    EJB is an overloaded name. Depending on the context, it represents either a server-side component, or component-based architecture. We’ll use the terms EJB, Enterprise Bean, and Enterprise JavaBean interchangeably in this book. Unless otherwise mentioned, we’ll use the term bean to mean EJB.

    The following are the characteristics of EJBs:

  • They contain business logic that operates on the enterprise’s data.

  • They depend on a container environment to supply life-cycle services for them. EJB instances are created and maintained by the container.

  • They can be customized at deployment time by editing the deployment descriptor.

  • System-level services, such as transaction management and security, are described separately from the enterprise bean.

  • A client never accesses an enterprise bean directly; the container environment mediates access for the client. This provides component-location transparency.

  • The EJB is designed to be portable across EJB servers provided by different vendors.

  • They can be included in an assembled application without requiring source code changes or recompilation of them.

  • Beans are always single threaded; you never have to write thread-safe code. You design your threads as single-threaded components, and the EJB container handles multiple client requests by load balancing and instantiating multiple instances of the single-threaded components.

    EJB Architecture Overview

    The J2EE architecture is a consolidation of standards, specifications, frameworks, and guidelines to provide Java capability on the server side for the enterprise. These standards and frameworks consist of classes and interfaces to be implemented by both service providers and developers. The EJB API is at the heart of the J2EE architecture. The other APIs are used as services to the EJB API. Many middleware vendors have been delivering implementations of the server-side APIs for the last few years.

    A J2EE implementation can be obtained from many vendors today. The implementation of the J2EE specification is realized through a Java application server, a product that offers the infrastructure-base solutions to the enterprise needs. The most common application servers today are BEA’s WebLogic Server, IBM’s WebSphere, and the open source JBoss.


    J2EE offers enterprise applications a higher level of abstraction. Not only does it offer portability of server-side component-based applications, but it also offers built-in common services to support all aspects of an infrastructure.


    The company Flashline provides an application server comparison matrix for an up-to-date look at the current and future releases of all application servers. You can access the comparison matrix at

    Figure 1.1 depicts how Java benefits both the client and the server. The Java Virtual Machine (JVM) abstracts applications on the client from the underlying environment and operating systems. On the server side, the J2EE application server offers common infrastructure services to enterprise applications.

    Figure 1.1. Java on the client and on the server.
  • The J2EE technology addresses the following enterprise component types (which could certainly be expanded in future releases of its specification):

  • Application clients. These are standalone client-side Java applications, which are hosted on client machines, and can use any relevant J2EE server-side functionality.

  • Applets. These are tiny client-side components hosted by a Web browser, and are mainly convenient to use in initiating services and then displaying the results to the user.

  • Servlets and JavaServer Pages (JSP). Servlets are server-side Java components that process requests on behalf of the users. Servlets invoke arbitrary services and process the results through the generation of HTML output to be displayed on a Web browser. JSP is a convenient API for embedding Java within HTML pages, from which the JSP implementation generates servlets.

  • Enterprise JavaBeans. EJBs are server-side components for encapsulating an application’s business logic. An EJB can offer specific enterprise service either alone or in conjunction with other EJBs. EJBs can be packaged together to be available to deliver transactional and secure enterprise applications over the network to other J2EE applications or services.

These components span multiple tiers, and a full coverage of multitier architecture and the J2EE architecture will be discussed on Day 15, “Understanding J2EE Architecture.” It’s worth noting here that the introduction of browser-based clients, such as applets and form-based JSPs, has contributed to accessing application functionality that’s hosted on a remote server through a unified form-based interaction. This shift from providing core corporate functionality at the PC and workstation level to the server via remote access has intensified the focus on server-side software.


Web-based applications have contributed to increased portability from a user-interface point of view. You can access your application functionality and data using a unified client agent (Web browser).

Comparing EJB with JavaBeans Components

The JavaBeans concept was developed to support reusable components in the Java programming environment. Because JavaBeans are used to build GUI components, JavaBeans components might be thought of as a client-side technology. However, JavaBeans are not required to be visual and they can be used in server environments.

JavaBeans are Java classes that have the following characteristics:

  • Support visual software development tools: The class must expose variables (called properties), methods, and events.

  • Customizable: This includes support for default property editors or provision for unique custom routines. Customization permits developers to change the behavior of a bean without changing the source code.

  • Support introspection: This refers to disclosing properties, methods, and events to other classes.

  • Persistent: This permits a bean to be saved in its customized state.


JavaBeans are not part of the J2EE architecture. They’re being used for a while as a data bean to transfer data from EJB components to Web components. JavaBeans are also used in a few J2EE design patterns.

JavaBeans are used in the J2EE applications as either a view bean or as a data bean. The most common examples of a view beans are in designing a GUI. For example, a GUI button widget could be developed as a JavaBean. Development tools can use introspection to examine the button bean’s properties such as label and color. You also can use these tools to set the bean’s behavior to respond to the user event of clicking on the button. A data bean can be used as a data container to transfer data between a servlet and an EJB. To process a user request, a servlet invokes an EJB with the request, and business data is populated into a data bean to be displayed as a response to the user.

The only similarity between an EJB and a JavaBean is that both are components. An EJB does not have the same structure as a JavaBean. An EJB consists of two interfaces and two classes, whereas a JavaBean consists of only one Java class. A JavaBean is local to a single process and can’t be shared by multiple users, while some types of EJB are shareable.


It’s important to understand that Enterprise JavaBeans are different from ordinary JavaBeans. Unfortunately, the use of the term JavaBeans causes much confusion. EJBs, servlets, and JSP components have more in common with each other than with JavaBeans.

Why EJB?

The EJB architecture allows enterprise applications to be portable by running on a J2EE-compliant application server. An EJB application can be partitioned in a more usable, flexible, and expandable fashion. For example, new clients to access legacy systems can be easily built to meet user requirements. Moreover, the EJB architecture helps create a service-based model in which services are location-transparent components that can be delivered to their target clients. EJBs are highly reusable components, and represent the next step in the progression of Java technology for the development of application platforms capable of supporting mission-critical, component-based, enterprise applications. EJB components allow the development of business logic to be used across enterprise applications and to be portable across different platforms.

The EJB model is based on Java Remote Method Invocation (RMI) technology, which supports the separation of executable components across multiple tiers. This separation permits maximum implementation flexibility and high scalability. RMI allows access to remote components to appear as if it were local to the invoking client. Moreover, the introduction of infrastructure services provided by the container help to manage and offer such services to the deployed EJBs. These runtime services make it possible for the EJB developer to focus on writing robust and reliable applications.

The following summarizes the benefits gained by the enterprise and developers from using EJB technology:

  • Simplicity: The EJB architecture simplifies the development of complex enterprise applications by providing built-in common services. This allows an EJB application developer to access and utilize these services, and results in a reduction of the overall development effort.

  • Application portability: Portability can be accomplished by deploying an EJB application on any J2EE-compliant application server. Many Java application servers today implement all the services provided by J2EE-standard specifications.

  • Component reusability: An EJB is a highly reusable building block. J2EE applications can be composed of custom-based EJBs, off-the-shelf EJBs, or both. In addition, the application business logic of a certain EJB can be reused through Java subclassing of the EJB class.

  • Application partitioning: The separation of an application’s business logic from its presentation allows ease of development and helps business programmers to work independently from Web page designers. Again, the separation of the application’s business logic from its data helps manage each team independently. Any change of a component hosted in one tier does not affect the other tiers.

  • Distributed applications: The EJB architecture helps create distributed applications, which can span multiple environments. Each subsystem can work independently of the others, but still can interact with one another to deliver enterprise services to the target users. A user transaction, for example, can be executed across multiple servers within a single context, and will be perceived by the user as a single unit of work.

  • Application interoperability: The EJB architecture helps EJB components to access other components written in other component-based models, such as CORBA and .NET.

  • Application integration: One of the main objectives of the EJB architecture is to allow the integration of new applications with existing applications, such as legacy systems. Today, Enterprise Application Integration (EAI) is a hot topic for the corporate world. The related J2EE APIs, such as the J2EE Connector Architecture (JCA) and the Java Message Service (JMS) specification, make it possible to integrate enterprise bean applications with various non-Java applications, such as ERP systems or mainframe applications, in a standard way.

  • Availability of Java application servers: An enterprise has many J2EE-compliant application servers to choose from. Each application server provides J2EE services at a minimum, with the addition of other value-added services. A J2EE-compliant server can be selected to meet the customer’s needs, which prevents vendor lock-in.

The most significant value provided by the EJB architecture is the separation of business logic programming from the challenge of integrating business logic with the complexities of enterprise-class server-side runtime environments. If the containers in which EJB components are deployed assume responsibility for managing runtime services such as persistence, transactions, and concurrent database access, bean developers are free to focus on developing software components that encapsulate business logic.

The EJB architecture is flexible enough to implement components such as the following:

  • An object that represents a stateless service, which is modeled using a stateless session bean.

  • An object that represents a stateless service whose invocation is asynchronous and driven by the arrival of enterprise messages. This is modeled by EJB with a message-driven bean.

  • An object that represents a conversational session with a particular client. Such session objects automatically maintain their conversational state across multiple client-invoked methods. This is modeled by EJB with a stateful session bean.

  • An entity object that represents a business object that can be shared among multiple clients, which is modeled with an entity bean.

  • An entity object that represents a fine-grained persistent object that embodies the persistent state of a coarse-grained business object. This is also modeled with an entity bean.

EJB introduces the following flavors of beans (see Figure 1.2):

  • Session beans, which are divided into stateless session beans and stateful session beans

  • Entity beans, which are divided into bean-managed persistence and container-managed persistence

  • Message-driven beans

Figure 1.2. Flavors of EJBs.

Later in this book, you’ll be provided with a more detailed explanation of each bean type. But for now, as a general rule, a session bean represents a user session (stateful or stateless), and implements the workflow of an arbitrary business process. An entity bean, on the other hand, represents a data row (record), in a database that can be accessed to satisfy user requests. Although both session and entity beans are synchronous in nature, message-driven beans are used to receive asynchronous messages, and process them accordingly.

EJB Design Goals

Since its inception by Sun Microsystems in 1997, the EJB architecture has had the following goals:

  • To be the standard component-based architecture for building distributed object-oriented business applications in the Java programming language.

  • To make it easy to write enterprise applications. Developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs.

  • To enable an EJB to be developed once, and then deployed on multiple platforms without recompilation or source code modification.

  • To address the development, deployment, and runtime aspects of an enterprise application’s life cycle. Also, to define those contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime.

  • To be compatible with existing server platforms and with other Java programming language APIs.

  • To provide interoperability between EJBs and J2EE components as well as non-Java programming language applications.

  • To be compatible with the CORBA protocols.

    Looking Inside an EJB

    Generally, an EJB consists of two interfaces and one class. The interfaces are the home and component interfaces, and the class is the bean class. Figure 1.3 illustrates what’s inside an EJB, and how a client interfaces with it.

    Figure 1.3. Looking inside an EJB.

    The home interface lists the available methods for creating, removing, and finding EJBs in the container. The home object is the implementation of the home interface that’s generated by the container at deployment time. At runtime, the home object will be used by the client in conjunction with a naming service to find the component and establish a connection to its component interface.

    The component interface defines the business methods offered by a bean class. Note that the bean class does not directly implement this interface but, rather, uses an EJBObject class that mediates the client’s calls to a bean object. The container provides the implementation of this interface, and the client (in conjunction with a naming service to find the component and establish a connection to its component interface) will use it. The component interface can be either remote or local, depending on the location of the EJB client with respect to the EJB. This distinction is made to avoid network traffic due to remote calls.

    The bean class is the implementation of the business methods listed in the component interface. It’s accessed by the client through the component interface; it’s not accessed directly.

    The primary key class (not shown in Figure 1.3) is used only for entity beans, and is provided only if the underlying data table has a segmented key.

    The EJB client locates the EJB containers through the JNDI service, and it interfaces with the EJB through the objects generated by the container. After an EJB client finds a reference to an EJB home interface, it can retrieve the EJB component interface. It can then issue business methods on the EJB component interface, which the container in turn delegates to the bean itself. EJB clients can be servlets, JSPs, or Java application clients.

    Additional interfaces defined in the EJB specification allow beans to interact with the transaction service and control persistence if they are designed to do so. For simplicity, these interfaces are not shown in Figure 1.3.

    The EJB container hosts enterprise beans, providing life cycle management and services such as caching, persistence, and transaction management.

    EJB Server

    The EJB server (also known as the J2EE application server) is the outermost container of the various elements that make up an EJB environment. The EJB server manages one or more EJB containers and provides required support services, such as transaction management, persistence, and client access. A JNDI-accessible naming space can be used by clients to locate the EJB. Figure 1.4 illustrates a J2EE application server.

    Figure 1.4. J2EE application server.

    The J2EE application server also provides operation resources, such as process and execution threads, memory, networking facilities, system resource management, connection pooling and caching, load balancing, fail-over, and so on to the containers and the elements within them. The EJB server can offer further vendor-specific features, such as optimized database access drivers, interfaces to backend systems, and CORBA accessibility.


    According to the current EJB specs, there’s no clear distinction between an EJB container and an EJB server. An EJB server can run multiple containers of different types.

    A number of J2EE application servers are available today, such as BEA’s WebLogic Server, IBM’s WebSphere, and the open source JBoss.

    EJB Containers

    An EJB container is an abstract facility that manages instances of EJB components. The EJB specification defines the contractual agreement between the EJB and its container to provide both infrastructure and runtime services. Clients never access beans directly: Access is gained through container-generated methods, which in turn invoke the beans’ methods. A container vendor may also provide additional services implemented in either the container or the server.

    Essential EJB Container Services

    All EJB instances run within an EJB container. The container provides system-level services to its EJBs and controls their life cycle. Because the container handles most system-level issues, the EJB developer does not have to include this logic with the business methods of the enterprise bean. In general, J2EE containers provide three main types of services: common vertical services, common horizontal services, and common deployment tools (refer to Figure 1.4).

    In the next few sections, we’ll discuss the definition of these services. We’ll discuss some of the services in detail in the following days.

    Common Vertical Services

    The common vertical services are inherent services that are provided by the EJB container and are not specified explicitly by the J2EE architecture APIs. They contribute to the performance and runtime aspects of the EJBs and the services provided to them. EJB developers need not include any logic to manage these services. The following is a list of these common services:

  • Life cycle management: The container creates and destroys enterprise bean instances based on client demand. This is done to maximize performance and minimize resource usage such as memory. In addition, a container may transparently multiplex a pool of instances to share among several clients.

  • Security: The security services are designed to ensure that only authorized users access resources. J2EE specifies a simple role-based security model for enterprise beans and Web components. In addition, vendors typically provide integration with third-party security providers such as LDAP.

  • Remote method invocation: The container transparently manages the communication between enterprise beans and other components. So, you do not have to worry about low-level communication issues such as initiating the connections, and marshalling/unmarshalling the method parameters. A bean developer simply writes the business methods as if they’ll be invoked on a local platform.

  • Transaction management: The transaction services relieve the enterprise bean developer from dealing with the complex issues of managing distributed transactions that span multiple enterprise beans and resources such as databases. The container ensures that updates to all the databases occur successfully; otherwise, it rolls back all aspects of the transaction.

  • Persistence: Persistence services simplify the connection between the application and database tiers. Container-managed persistence of entity beans simplifies the coding effort for application developers.

  • Passivation/activation: The mechanism that is used by the container to store an inactive enterprise bean to disk, and restore its state when the bean is invoked. The container uses this mechanism in support of both entity and stateful session beans. This allows the servicing of more active clients by dynamically freeing critical resources such as memory.

  • Clustering: Supports replication of EJBs and services across multiple application server instances installed on the same machine or in different environments. Clustering involves load-balancing the requested services and EJBs among the replicated instances. It also supports fail-over—should one instance fail, the load will be picked up by another.

  • Concurrency: Supports multithreading management. All components must be developed as single-threaded, and the container manages the concurrency and serialization access to the shared resources.

  • Resource pooling: Supports the allocation of a pool of instances, and then assigns them to the requesting clients. When an instance is free, it goes back to the pool. This is applied for JDBC connections, stateless session beans, and entity beans.

Common Horizontal Services

Common horizontal services are the services specified in the J2EE architecture. They’re commonly known as J2EE APIs, and are provided by the EJB server to all the containers running on the server. Here’s the standard list of the J2EE APIs:

  • Java Naming and Directory Interface (JNDI): Provides Java-technology-enabled applications with a unified interface to multiple naming and directory services in the enterprise.

  • Java Database Connectivity (JDBC): Provides access to virtually any tabular data source for J2EE applications.

  • JavaServer Pages (JSP): Enables Web developers and designers to rapidly develop and easily maintain information-rich, dynamic Web pages that leverage existing business systems.

  • Java Servlet: Provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems.

  • Java Transaction API (JTA): The standard Java interfaces between a transaction manager and the parties involved in a distributed transaction system: the resource manager, the application server, and the transactional applications.

  • Java Message Service (JMS): A common API and provider framework that enables the development of portable, message-based enterprise applications.

  • J2EE Connector Architecture (JCA): The key component for enterprise application integration in the Java platform. In addition to facilitating enterprise application integration, the JCA helps to integrate existing enterprise applications and information systems with Web services and applications.

  • Java API for XML Processing (JAXP): Enables applications to parse and transform XML documents independent of a particular XML processing implementation.

  • RMI over IIOP (RMI/IIOP): Delivers Common Object Request Broker Architecture (CORBA) distributed computing capabilities to the J2EE platform.

  • Java Authentication and Authorization Security (JAAS): Enables services to authenticate and enforce access controls upon users.

  • JavaMail: Provides a platform- and protocol-independent framework for building Java-technology-based mail and messaging applications.

  • JavaBean Activation Framework (JAF): Standard services used by JavaMail to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and instantiate the appropriate bean to perform said operation.

Common Deployment Tools

These are the deployment services and tools provided by the EJB server; they are also available to the container. Here’s a list of these services:

  • Deployment tools: These are used to compile and deploy J2EE applications. They unpack the application package file and interpret all the runtime properties to install the EJB and other components of the applications.

  • Object-relational mapping tools: A new generation of tools, such as TopLink, that map relational data in a database to its object counterpart properties in memory.

  • Monitoring tools: These are used to monitor applications while they are running. Such tools are vital to checking the health of your application, and enable you to provide solutions when issues arise.

    Understanding EJB Roles

    The EJB specification defines different roles in the development, assembly, and deployment of enterprise applications. The EJB architecture simplifies the development of complex business systems by dividing this process into six distinct roles, each with a specific task and objectives. These six roles address application development, infrastructure services, and deployment issues. Figure 1.5 illustrates the different roles involved in developing and deploying EJB components and applications.

    Figure 1.5. The EJB roles and their responsibilities.

    In the next few sections, we will discuss these roles in more detail.

    Application Development Roles

    The task of building large component-based applications is typically divided into developing new components followed by the assembly of those components with existing reusable components. Some of the existing components could be components-off-the-shelf (COTS). The EJB architecture makes a clear distinction between the EJB developer (bean provider) and application assembler, even when, as in many cases, these two roles are combined and performed by one person or team.

    EJB Developer (Bean Provider)

    The EJB developer is typically a domain expert with knowledge of the business rules, such as the financial or pharmaceutical industry. The EJB developer implements the business logic represented by the EJB’s business methods, and defines the EJB’s interfaces and deployment descriptor. The EJB developer defines a client view of an EJB. The client view is unaffected by the container and server in which the EJB is deployed. This ensures that both the EJBs and their clients can be deployed in multiple execution environments without code changes or recompilation.

    Application Assembler

    The application assembler is a domain expert who assembles an application from many building blocks (such as EJBs, servlets, JSP, applets, and Java clients) to complete the application. An assembler is primarily concerned with the interfaces to EJBs (the home and remote interfaces) and with the EJB’s deployment descriptor. The assembler is responsible for configuring both the security and transactional aspects of the EJBs in the deployment descriptor.

    Infrastructure Roles

    The infrastructure roles address the container, application server, and deployment tools. These tasks are typically provided by a vendor with expertise in distributed infrastructures and services who implements a platform that facilitates the development of distributed applications and provides a runtime environment for these applications.

    EJB Container and Server Provider

    This is an expert in distributed systems, transactions, and security who provides deployment tools for EJBs and runtime support for these deployed instances. A container is a runtime system for one or multiple EJBs that provide common services such as transaction, security, and lifecycle management. A container includes code and a tool that generates code particular to a particular enterprise bean. It also provides tools to deploy an EJB and a means for the container to monitor and manage the application.

    Deployment Roles

    The EJB specification makes a clear distinction between the deployment roles because the cost of application deployment is much higher than application development.


    The deployer (a new word for most dictionaries) adapts an application, composed of a number of EJBs, to a target operation environment by setting the properties and behaviors of the EJB. For example, the deployer sets properties in the deployment descriptor that determine transaction and security policies. The deployer also integrates the application with existing enterprise monitoring and management software. The deployer must be familiar with both the application operational requirements and the application server environment.

    System Administrator

    The system administrator configures and administers the enterprise applications and infrastructure, including the application server, networking, databases, and Web servers. The administrator monitors the running application and takes appropriate actions in the event that the application behaves abnormally. Typically, an administrator uses enterprise monitoring and management tools that are connected to the application by the deployer through the hooks provided by the container.


    A traditional application programmer now becomes an EJB developer and, possibly, an application assembler. These tasks enable the programmer to focus on the business problem and business logic. The deployer defines and sets the deployment policies when installing the EJB. The complexity of implementing mechanisms for executing the deployment policies is delegated to the container provider. Although distributed applications remain complex, the application programmer’s job becomes easier because much of the complexity is addressed by EJB server and container providers.

    The various roles are not always performed by different people. In large applications, different individuals or teams might execute each of the roles. In some scenarios, such as small applications, a single person might perform multiple roles. During your 21-day journey of learning EJB, you’ll execute multiple roles such as enterprise bean provider, application assembler, deployer, and system administrator. You’ll use the EJB container and server provided by BEA’s WebLogic Server or the JBoss organization’s open source code application server, JBoss.

    Deployment Process

    The efforts involved in developing and deploying an EJB require the following multi-step process:

    1. Define all business methods in the component interface. This can be either a remote or local interface, depending on the design strategy you implement. A remote interface enables you to make your applications distributed in nature. A local interface allows access to the EJB from the same JVM.

    2. Define the home interface of your EJB, which includes all the life-cycle management methods of the EJB, such as creation, location, and removal of the EJB.

    3. Implement the business methods in the bean class. Other callback methods might be required for some types of EJB.

    4. Create your EJB’s deployment descriptor, which allows for the declaration of the EJB type, and transaction and security attributes.

    5. Compile your EJB classes and interfaces.

    6. Package the compiled EJB objects into a JAR file along with the deployment descriptor.

    7. Deploy the EJB into the EJB container.

    For all the examples in this book, we provide a script to carry out all the steps from 5–7. In addition, we provide a script to run the EJB client we develop in each day of our journey to learn EJB.


Day 21. Developing a Complete Enterprise Application


Today, you’ll develop a complete enterprise application. You’ll apply different concepts you learned in the previous days to build an application that consists of Web components (JSPs and servlets), EJB components (session, entity, and message-driven enterprise beans), and the EIS tier (database tables).

The sample university registration system is an end-to-end application that handles the online course registration and enrollment process in a transactional e-commerce environment.

Today you’ll see how to perform analysis, design, implementation, and deployment of the sample application. You’ll undertake each of the following:

  • Understand the application requirements

  • Perform use case analysis

  • Decide on a system architecture that meets the application requirements

  • Identify the components in the multitier architecture and the interactions among these components

  • Implement the components, and package and deploy the application

Understanding the Application

The university registration system is a typical e-commerce application. The application has a Web site that enables students to browse the course catalog and register for courses online. Figure 21.1 shows an overview of the system.

Figure 21.1. University registration system.

The application provides the following functionality:

  • Student registration— This functionality enables new students to create and maintain their account information. The account information includes the student’s first name, last name, address, e-mail, login name, and password.

  • Student authentication— This module handles the student login process, such as verifying the login name and password. This ensures that only registered students browse the course catalog and purchase courses for enrollment.

  • Course catalog browsing— The Web site displays the current course offerings in the university and their details. The course details include the course title and fee.

  • Enrollment cart— The enrollment cart module enables students to place their course selection in a shopping cart while browsing the course catalog, and later to view the cart contents before placing an order.

  • Order processing— The order module enables students to place their orders, and performs the necessary verification before approving them.

  • Administrator interface— This functionality allows the administrator to view and approve orders for enrollment.

  • Notification— This functionality causes the system to send e-mail to students when they have enrolled for a course.

Analyzing the Application

Use case analysis is the standard technique for analyzing the requirements of an application. A use case diagram shows the interaction between the system and actors. An actor is a role that human and/or nonhuman users of the system play when interacting with use cases. Figure 21.2 shows a high-level use case diagram of the university registration system.

Figure 21.2. Use case diagram.

The use case diagram in this case consists of actors, such as student, administrator, and order verification system. The following describes the use cases:

  • New students register with the system.

  • Existing students log on to the system and can browse the course catalog.

  • A student can select courses and add them to the enrollment cart.

  • A student places an order for the enrollment cart contents.

  • The system verifies the order in the background.

  • An administrator can view the verified orders that need approval for enrollment.

  • An administrator approves the order and enrolls the student in the courses.

  • The system notifies the student of enrollment via e-mail.

Architecting the System

Architecting consists of deciding what tiers are needed for the application, what services are required at each tier, and how the application logic will be spread across different tiers. As you learned on Day 15, “Understanding J2EE Architecture,” the J2EE architecture is designed for multitier applications. In a multitier architecture, the business logic can be split into more than one layer. In the sample application, logic is partitioned into the business logic tier and the presentation logic tier. The user interface is partitioned into the client tier and the presentation tier. The application-persistent data is stored in the EIS tier. Figure 21.3 shows the architecture of the system.

Figure 21.3. Architecture diagram.

The sample architecture consists of the following tiers:

  • Client tier— Students and administrators use the client tier to interact with the system. The client tier is provided by a Web browser, such as Internet Explorer or Netscape Navigator. The client tier communicates with the Web tier by using the HTTP protocol.

  • Web tier— This tier accepts user requests and generates responses using the presentation logic. The sample application uses both servlets and JSPs in a Web container. The Web tier communicates with the business logic tier using RMI/IIOP protocol.

  • Business logic tier— This tier handles the core business logic of the application. The business components are implemented as EJB components with support from an EJB container.

  • EIS tier— The EIS tier consists of the database in which the sample application’s permanent data is stored. The business-logic tier communicates with the EIS tier using JDBC.


J2EE offers flexibility in partitioning the application logic across tiers. For example, you have a choice between Web-centric and EJB-centric design. In the Web-centric design, the Web tier components are responsible for most of the application’s functionality. The Web tier components communicate directly with the EIS tier using container services such as the JDBC API. In the EJB-centric design, the enterprise beans encapsulate the core application logic. Web tier components communicate with EJB tier components instead of accessing the EIS tier directly.

The decision between the Web-centric and EJB-centric approaches depends on factors such as application functionality and scalability requirements. The Web-centric approach offers a quick start for small applications, but can rapidly become complex and difficult to maintain for large applications. The EJB-centric approach offers advantages such as automatic handling of transactions, distributed processing, security, and so on, and can stay manageable as applications grow more complex. The sample application uses the EJB-centric approach.

Designing the Application

Next, you must decide what components are needed in each tier and how they interact with each other to achieve the required functionality.

Figure 21.4 shows the high-level design of the application. Please note that this diagram does not show all the components and their interactions. The diagram shows JSPs, servlets, enterprise beans, and database tables. The following sections discuss the various components in detail.

Figure 21.4. Application design.

Designing the Business Logic Tier Components

The following discusses the key enterprise beans in the business logic tier:

  • The concept of the student is central to the university registration application. Multiple clients must share behavior, such as creating a student account, verifying an existing account, and updating account information. Updates to the state of a student object must be written to the persistent store. The student object must live even when the client’s session with the server is over. Therefore, the Student component is modeled as a container-managed persistence entity bean.

  • SignOn is the authentication component that verifies the user login name and password. This component uses the User component to retrieve and store the user’s login name and password. Such a component doesn’t need to maintain client-specific state information across method invocations, so the same bean instance can be reused to service other client requests. This can be modeled as a stateless session bean.

  • The Course component models the courses offered by the university. Because courses are persistent objects, Course is modeled as a container-managed persistence entity bean.

  • EnrollmentCart models the shopping cart concept in a typical e-commerce Web site. While browsing the course catalog, a student can add courses to and remove courses from the EnrollmentCart. A cart must be allocated by the system for each student concurrently connected to the Web site. All the selected courses of a student will be added to the temporary cart. This cart is not a persistent object because the student can choose to abandon the cart. Therefore, in the application, EnrollmentCart is modeled as a stateful session bean. Alternatively, if you want the enrollment cart to survive a client machine or server crash, you must model it as an entity bean.

  • A student places an order when he/she is ready to purchase the enrollment cart contents. The Order component must live even when the student’s session with the application is over. Therefore, the Order component is modeled as a container-managed persistence entity bean.

  • A student’s order consists of one or more line items. Each line item represents a single course item that the student has ordered. This is modeled as the OrderLineItem component. Similar to Order, OrderLineItem must persist even when the student’s session with the application is over. Therefore, OrderLineItem is modeled as a container-managed persistence entity bean. Also, the Order entity bean has a one-to-many bidirectional relationship with OrderLineItem. This relationship is modeled as a container-managed relationship.

  • The OrderVerifier component is responsible for verifying the order’s facts, such as the student’s billing information, the classroom’s capacity, and so on. We would like to enable the student to continue browsing the Web site and not require her to wait for the background processing to complete. This asynchronous processing can be best modeled using a message-driven bean. In the sample application, after the student submits an order, a Java Message Service (JMS) message is sent to a destination, where it will be processed by an OrderVerifier message-driven bean.

  • A student can enroll in multiple courses and each course can have many students enrolled in it. The Enrollment CMP component models the join relationship between the students and the courses. The Student entity bean has a one-to-many relationship with Enrollment and the Course has a one-to-many relationship with Enrollment.

  • The Mailer component is the stateless session bean responsible for sending e-mail messages. The AdminFacade component uses Mailer to send an e-mail confirmation to the student when the administrator approves the order for enrollment.

  • The StudentFacade component provides a unified interface to student functionality. Instead of communicating directly with enterprise beans such as Student and Order, clients go through the simpler interface of StudentFacade. StudentFacade is modeled as a stateful session bean.

  • The AdminFacade component provides a unified interface to the administrator functionality. Web components use a single AdminFacade component to access the administrator functionality. This component is modeled as a stateful session bean.


    The sample application uses the following approach for the business logic tier design.

  • Provides a simple interface to complex functionality by using session bean façades.

    The session bean façades front the entity beans. For example, the StudentFacade session bean provides a simple interface to student functionality and fronts entity beans such as Order.

  • For portability and ease of development, container-managed entity beans are used instead of bean-managed persistence entity beans. Also, all entity beans provide local interfaces for efficient access due to co-location.

  • Uses distributed islands of local components. For example, as shown in Figure 21.5, one such island is composed of components such as StudentFacade, SignOn, Course, and Order. All the components within this island communicate with each other by using local interfaces. This offers the benefit of higher performance. An island communicates with a remote island by using remote interfaces, which offers the benefit of scalability.

    Figure 21.5. Distributed islands of local components.

Designing the Web Tier Components

The following section discusses the Web tier components in the sample application:

  • The primary role of URSControllerServlet servlet is to act as a controller. This component is responsible for receiving parameters from the client and then invoking the calls to the EJB tier, which handles the business logic. Finally, the servlet receives the result and uses it to provide a response to the user. This servlet usually forwards the response to a JSP to perform a presentation task.

  • The application contains the JSP pages, such as the registration page, login page, course catalog page, enrollment cart page, and order confirmation page. These components contain the presentation logic for student-related functionality. In addition, the admin page contains the presentation logic for administrator-related functionality.


The sample application uses the MVC (Model-View-Controller) design pattern discussed on Day 7, “Designing Web Applications.” The model layer contains the enterprise bean components that handle the core business logic. The view layer contains the JSP pages, whose job is to format and present responses to the client. The controller layer provides the URSControllerServlet servlet, which is responsible for receiving the client request, managing screen flow, and selecting an appropriate response.

Designing the EIS Tier Database Schema

Figure 21.6 shows the database tables and the relationships between them. Each table is shown as a solid rectangle with two compartments. The top compartment holds the table name and the bottom compartment holds a list of column names. The primary key column(s) uniquely identifies a row in the table. We use the abbreviation PK for the primary key. The foreign key column of a table identifies a row in a different table. We use the abbreviation FK for the foreign key.

Figure 21.6. Database schema of the sample application.

For example, the enrollments table consists of the columns enrollment_id (primary key), student_id (foreign key to student_id in the students table), and course_id (foreign key to course_id in the courses table).

Designing the Scenarios

This section examines the interactions between components for key use case scenarios.

Student Logs On to the System

Figure 21.7 shows the sequence diagram for the use case Student Logs On to the System. The student enters a login name and password, and clicks the submit button in the login page. The browser sends an HTTP GET request to the Web server. The URSControllerServlet servlet receives the client request and invokes the validateUser() method of the StudentFacade enterprise bean. The façade delegates the method call of the SignOn authentication component, which uses the User entity bean to look up and validate the login name and password. Finally, the controller servlet forwards the request to the catalog page, which displays the course catalog.

Figure 21.7. Student Logs On to the System sequence diagram.

Student Places Order

As shown in Figure 21.8, when the student clicks the Place Order button in the enrollment cart page, the URSControllerServlet receives the request and invokes the placeOrder() method of StudentFacade. The façade first creates a new order using the Order entity bean. The façade then creates multiple line items using the OrderLineItem entity bean and associates the line items with the order. Finally, the façade sends a JMS message to the Destination using the MessageSender component for order verification purposes.

Figure 21.8. Student Places Order sequence diagram.

Administrator Approves Order and Enrolls Student in Courses

Figure 21.9 shows the sequence diagram corresponding to the use case Administrator Approves Order and Enrolls Student in Courses. When the administrator approves an order placed by the student, he or she clicks the Approve Order button on the administrator page. The URSControllerServlet receives the corresponding request and invokes the method approvedOrder of AdminFacade. The façade retrieves the order by using its primary key, order_id, and changes the order status to Approved. The façade then enrolls the student in all the courses that are part of the order by using the enrollment component. Finally, the façade sends an e-mail to the student confirming the approval.

Figure 21.9. Administrator Approves Order and Enrolls Student sequence diagram.

Packaging and Deploying the Application

This section describes the steps to package and deploy the application for both WebLogic Server and JBoss application servers. These steps assume that you configured OrderVerifierTopic as discussed on Day 14, “Developing Message-Driven Beans,” and ursMailSession as discussed on Day 20, “Implementing JavaMail in EJB Applications.”

You can run the following commands for WebLogic:

C:\>cd styejb\examples
C:\styejb\examples>cd day21

You can run the following commands for JBoss:

C:\>cd styejb\examples
C:\styejb\examples>cd day21

Running the Sample Application

The following steps describe how to start the PointBase database server and WebLogic Server, and run the sample application:

  1. Start PointBase server in a new command window as follows:

    C:\>cd styejb\examples

  2. Start WebLogic Server in a new command window as follows:

    C:\>cd styejb\examples

  3. Open the university registration system URL, http://localhost:7001/urs, using a Web browser. This will display the main page as shown in Figure 21.10.

    Figure 21.10. Sample application main page.

  4. Register a new student by clicking the New students register here link. Enter tom for the login name and tom for the password. Enter a first name, last name, address, and email for the student. Figure 21.11 shows the corresponding screenshot. Click the Register button.

    Figure 21.11. Sample application registration page.

  5. Figure 21.12 shows the course catalog page. Add a couple of courses to the enrollment cart by clicking the Add to cart link that corresponds to each course. Click the View your enrollment cart link to view the enrollment cart.

    Figure 21.12. Sample application course catalog page.

  6. Figure 21.13 shows the enrollment cart page. Click the Place Order link to purchase the cart contents.

    Figure 21.13. Sample application enrollment cart page.

  7. Now we’ll explore the administrator functionality. Open the URL http://localhost:7001/urs. Click the Administrator click here link. Figure 21.14 shows the administrator page displaying the verified order(s). Click the Approve link to approve the order and enroll the student in the courses.

    Figure 21.14. Sample application administrator page.

The following steps describe how to start the JBoss server and run the sample application:

  1. Start the JBoss server in a new command window as follows:

    C:\>cd styejb\examples

  2. Open the university registration system URL, http://localhost:8080/urs, using a Web browser. This will display the main page as shown in Figure 21.10. The remaining steps are similar to those listed for WebLogic Server’s steps 4 through 7.

Best Practices

Local architecture is implemented with local enterprise beans. Distributed architecture is implemented with remote enterprise beans. Local architecture offers the benefit of higher performance for the same hardware, but it’s harder to scale and cluster. On the other hand, distributed architecture is easier to scale and cluster, but results in reduced performance for the same hardware. One possible solution is to create distributed islands of local components as in the sample application.


Today, you worked on a complete sample application. We explored the requirements of the sample university application and analyzed them using a use case approach. We decided to use the multitier architecture that J2EE offers. We also decided to use an EJB-centric design in which the enterprise beans encapsulate the core application logic. We identified those components and their interactions. Finally, we packaged, deployed, and ran the sample application.