Vous êtes sur la page 1sur 133

06/01/2003

J2EE Programming with Passion!

EJB Overview

In this session, we are going to talk about basic and high level concept and
architecture of EJB. We still have 2 or possibly 3 more sessions for talking
about session beans, entity beans, message driven beans, security,
transaction, and persistence of EJB technology in detail later on.

1
06/01/2003

Sang Shin
sang.shin@sun.com
www.javapassion.com/j2ee

Technology Evangelist
Sun Microsystems, Inc.
2

2
06/01/2003

Disclaimer & Acknowledgments


? Even though Sang Shin is a full-time employee of Sun
Microsystems, the contents here are created as his own
personal endeavor and thus does not reflect any official
stance of Sun Microsystems.
? Sun Microsystems is not responsible for any
inaccuracies in the contents.
? Acknowledgements
– Some slides are made from the contents of the book "Applied
Enterprise JavaBeans" Technology written by Kevin Boone (Sun
Microsystems)
– Some slides are made from the contents of J2EE tutorial
authored by Dale Green (Sun Microsystems)
– Some slides are made from the contents of EJB codecamp
material authored by Carol McDonald (Sun Microsystems) 3

3
06/01/2003

Revision History
? 02/07/2003: version 1, created (Sang Shin)
? 05/11/2003: version 2, Speaker Notes are revised. (Daryl Luk luk@ptc.com)
? To be done
– speaker notes still need to be refined

4
06/01/2003

Agenda
? What is and Why EJB?
? EJB Architecture
? Component and Container Architecture
? Types of Beans
– Session beans, Entity beans, Message-Driven Beans
? Roles
? Anatomy of a EJB module
? How client invokes methods of EJB
? RMI communication model
? Deployment Descriptor & Packaging
5

So this is the agenda for this presentation. First, we will talk about what is EJB and then why
and when you want to use EJB for the development and deployment of enterprise applications.
Then we will spend some time talking about EJB architecture especially from the standpoint of
component and container architecture. This component and container architecture is a rehash
of what we already talked about in “J2EE overview”.

We will spend sometime talking about types of beans a bit. There are three types of beans
currently: session beans, entity beans, and message driven beans. Each of these bean type
addresses specific area of writing enterprise application.

In building and deploying EJB application, there is a clear separation of roles. For example, the
role that is played by bean developer is different from the role that is played by the deployer.
And we will talk about these logical roles.

We will look into the anatomy of EJB module. That is, when you build EJB module, as a bean
developer, the question of “what do you have to include in that module?” will be addressed
here.

We will talk about a bit on the RMI communication model between the client and EJB server.
Along with it, we will talk about the difference between local client view and remote client view.

We will spend some time talking about deployment and packaging.


Finally we will talk about EJB security and transactions.

Again, we will talk about these issues in rather high-level today and later on in this class, these
issues will be addressed again in more detail. 5
06/01/2003

What is EJB?

So let's talk about what EJB is first.

6
06/01/2003

What is EJB? (From EJB Spec.)


? “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, then
then deployed on any server platform that
supports the Enterprise JavaBeans
specification." 7

This is the definition of EJB architecture from EJB specification. The key
point of EJB architecture is to provide server side component architecture
for building scalable, transactional, and multi-user secure enterprise
applications.

Because the applications are written in component architecture and in Java


programming language, there is a high degree of reusability of these
components.

7
06/01/2003

What is EJB Technology?


? Cornerstone of J2EE
? A server-side component technology
? Easy development and deployment of
Java technology-based application that
are:
– Transactional, distributed, multi-tier,
portable, scalable, secure, …

So this is a just a repeat of the previous slide. This is a bit short description of EJB.

What is EJB? In short, it is a server-side component technology, which enables the


easy development and deployment of Java-based enterprise applications in the form
of components that have to be enterprise-quality, meaning they are transactional,
distributed, multi-tier, portable, scalable, secure, and reliable, and the list can go on.

8
06/01/2003

EJB Design Principles


? EJB applications are loosely coupled
? EJB behavior is specified by interfaces
? EJB applications do not manage resources
? The container supports the application
developer
? EJB applications are tiered
? The session tier is the API to the application
? The entity tier is the API to the data sources

source: Applied Enterprise Beans Technology 9

Now let's talk a little bit on EJB design principles. (These design principles are
quoted from Kevin Boone's Applied Enterprise Beans Technology” Book,
chapter 1.)

9
06/01/2003

EJB applications are Loosely


Coupled
? Support the integration of components
from different vendors
? EJBs refer to other components and services
to which they have access by arbitrary
names
? EJB can be authored without a detailed
knowledge of the environment
? Applications can be assembled from
separate EJB's
source: Applied Enterprise Beans Technology 10

This is discussed at [EJB2.0 specification, chapter 5.4]. The EJB Specification was
designed from the outset to support the integration of components from different
vendors. For example, EJBs refer to other components and services to which they have
access by arbitrary names. These names can be mapped onto real names without
modifying program code. This allows EJBs to be authored without a detailed knowledge
of the environment in which they will be used, or of the other components with
which they will interact. In traditional software engineering, this principle is called
‘loose coupling’. A loosely-coupled system is easier to test and maintain, and its
components are easier to be re-used.

The Specification distinguishes carefully between the role of the ‘component


provider’ and the ‘application assembler’, even though these may be the same person or
people in practice. As we shall see, an ‘application assembler’ is someone who builds an
application from separate EJBs, perhaps from different sources. The assembler’s roles
include resolving naming conflicts between the different components, and ensuring that
transactions are propagated between components correctly. These factors are largely
controlled declaratively – in XML files – not in Java code, allowing applications to be
assembled without code changes.

10
06/01/2003

EJB behavior is specified by Java


interfaces
? An EJB’s interaction with its clients is
specified entirely in terms of Java interfaces
– Interfaces expose the methods that clients can
call, and thereby set out a ‘contract’ between the
client and the EJB
– Implementation is hidden from the client
– Supports portability and modularity

source: Applied Enterprise Beans Technology 11

The clients of EJBs do not, in principle, need access to the EJB implementation
code itself, either at compile time or run time. An EJB’s interaction with its
clients is specified entirely in terms of Java interfaces. These interfaces expose the
methods that clients can call, and thereby set out a ‘contract’ between the client
and the EJB. Developers who work with systems that do not enforce this strict
separation between ‘interface’ and ‘implementation’ sometimes find the use of
interfaces a burden in EJB development; nevertheless, it increases portability and
modularity, and makes it easier to support integration with non-Java components
(in which interfaces may be specified using IDL, for example).

11
06/01/2003

EJB applications do not manage


resources
? EJBs get access to external resources
(databases, legacy systems) through their
container
– Programmer does not have to worry about
resource allocation and de-allocation
? It is the container’s job to manage these
resources, and make the access as efficient as
possible
– Container is configured by system admin not
through programming APIs
source: Applied Enterprise Beans Technology 12

As far as possible, EJBs get access to external resources (databases, legacy


systems) through their container. It is the container’s job to manage these
resources, and make the access as efficient as possible. In most cases the container
will implement resource sharing and pooling schemes to support this. The
programmer does not have to worry about resource allocation and de-allocation.
The EJB server itself cannot be configured or managed through API calls; it is
the administrator’s responsibility to configure resource sharing policies, not the
developer’s.

12
06/01/2003

Container supports application


developer
? Container provides system services
– Persistence
– Security
– Transaction
– Connection pooling
– Component lifecycle management
– Threading
? Application developer and deployer specifies his/her
requirements in declarative fashion
source: Applied Enterprise Beans Technology 13

This is particularly important where persistence management and transaction co-


ordination is required. when version 1.1 of the EJB Specification was current,
developers were loathe to use container-managed persistence (CMP). in version
2.0, the CMP strategy has been radically revised. in it now possible to define
container-managed relationships between objects as well as container-managed
persistent data. these features are straightforward to use when fully understood,
and significantly ease the development process. however, for these advantages to
be fully realized, the developer must ‘buy in’ wholeheartedly, and develop in the
spirit of the EJB model.

13
06/01/2003

EJB in a
Big Picture of J2EE
14

Now let's take a look at where EJB fits in in the big picture of J2EE.

14
06/01/2003

Where is EJB?

Web Tier EJB Tier

15

This is the same picture we have seen during the J2EE overview session. As you
can see, the Servlet and JSP are web tier components that are running within web-
tier container. The role that web components play are basically receiving client
requests that are coming in the form of HTTP requests and then perform dynamic
contents generation or performing business logic by themselves or delegating it to
the EJB tier components.

15
06/01/2003

EJB, EJB Server, EJB Client


Web
Components EJBs

EJB clients
talking to EJB server

Web
Browser Components EJBs

DB & EIS
Resources
Stand-alone
Application

web-tier EJB client talking to EJB server


Standalone EJB client talking to EJB server
16

Now EJB clients are anything that invokes methods of EJB beans. EJB beans reside
in EJB server. The EJB clients can be standalone applications or web-tier
components. The EJB clients can be even other EJB beans.

16
06/01/2003

Why EJB?

17

17
06/01/2003

Why EJB Technology?


? Leverages the benefits of component-
model on the server side
? Separates business logic from system
code
? Provides framework for portable
components
– Over different J2EE-compliant servers
– Over different operational environments
? Enables deployment-time configuration
– Deployment descriptor 18

Why EJB? By providing a standard component model on the server side, it leverages all the
benefits that are inherent in component technology, for example, reusability of components,
availability of 3rd party components that you can assemble together to create applications,
availability of tools, and so on.

Another key benefit of EJB is the separation of business logic from system code. That is, the
EJB server platform provides all the system services such as resource management,
transaction coordination and persistence management. Since the system services are provided
by the server platform itself, you, as a developer, can now focus your development effort to
building business logic components rather than system code.

Because EJB is built around industry-standard component framework, and because it is based
on Java, it allows portability of your components. That is, the business logic components you
build will be portable across different vendors’ server platforms as well as different
operational environments without any change in your code or without even recompiling. It is
truly binary portability we are talking about.

Now you might want to ask? How do these components adapt themselves to the different
operational environments? That is, different operational environments have different
requirements on security policy, they have different databases in place, different transactional
model maybe have to be used. How do you instruct your business components to a different
behavior without actual change of code? It is done by what is called deployment descriptor.
The deployment descriptor is essentially an XML file that declaratively specifies the runtime
behavioral characteristics of your business component. And it gets constructed or changed at
the time of deployment, not at the time of code development.
18
06/01/2003

Enterprise JavaBeans
? Defined as business logic ONLY
? No low-level plumbing
? Reusable across multiple EJB Servers
? Implement interfaces that allow
container to manage them

19

So as a bean provider, basically what you have to focus your


development effort is to build business logic in the form of
Enterprise Java Beans. And you don't have to worry about low-
level plumbing because low-level plumbing is provided by the
container. Again, once you build your EJB beans, they should
be reusable over different EJB platforms.

Later on we will talk about this aspect several times because it is


a very important architectural concept. When you build your
EJB bean, you have to specify the two interfaces, home interface
and remote interface to specify the methods can be called by the
client. The actual implementations of these interfaces are
provided by the container not by the bean itself. Again, we will
talk about this concept later.

19
06/01/2003

Do You Need an EJB Tier?


? Yes, if you want to leverage middleware features
provided by container
– Resource management, instance life-cycle
management, concurrency control and threading
– Persistence, transaction and security management
– Messaging, scalability, availability
? Yes, if you want to build portable and reusable
business components
? Maybe not, for a simple application whose main
function is reading database tables
20

Many people are asking if they need to use EJB technology. I would say
that in some cases it makes sense to write a web-only application

As the needs and the complexity of a web-only application grows,


following issues arise
All the transactional work needs to be handled
The life-cycle of each object that gets created needs to be managed
If multiple objects access shared data, then that data needs to be
accessed in a thread-safe manner
All the code for data persistence needs to be written
Use EJBs to take advantage of system-level services for
Instance management (managed objects)
Concurrency control
Declarative security and transactions
EJBs provide an elegant component model that promotes software reuse.

20
06/01/2003

EJB Architecture

21

Now let's talk about EJB architecture.

21
06/01/2003

EJB Architecture

22

This picture shows a somewhat simplified architecture of EJB. We will talk about
the concept of containers and components later on. But a key architectural
concept of EJB is that there is a separation of business logic components from the
hosting environment in which those components are running. The business logic
components under EJB architecture are represented as EJB beans while the hosting
environment is represented by container or EJB server.

As a business component developer, you have to write three Java files. First you
have to write EJB home interface which defines the methods that will be used by
clients in order to create and locate your bean. Second, you have to write EJB
remote interface which defines the business methods of your bean. Finally, you
will build your bean.

Now container, at the time of deployment of your beans, will create two internal
objects, EJB home object and EJB remote object. These objects are
implementation of home and remote interface you have defined. So when the
client wants to invoke some business methods of the EJB bean you created, it is
actually talking to these two intermediary objects instead. Why this indirection?
This is to allow the container to intercept the calls so that it can provide system
services such as security, transaction, persistence, resource management, life cycle
management, and so on.

22
06/01/2003

EJB Architecture Contracts


? Contracts are specified in EJB specification
? Client view contract
– Contract between client and container
? Component contract
– Contract between an Enterprise Bean and its
Container

23

Now EJB specification talks about contracts. Concrete and precise


contracts are important because in EJB architecture EJB client application
expect certain set of behavior from EJB beans and vice versa is also true.

So specification talks about client view contract and component contract.


The client view contract specifies the contract between the client and the
container. And component contract specifies contract between the beans
and its container.

23
06/01/2003

Client View Contract


? Client of an EJB can be
– Web tier components: Servlet and JSP
– Standalone Java application
– Applet
– Another EJB in same or different container
– Web services client (in EJB 2.1)
? Provides development model for clients
using EJB services

24

The client of EJB can be anything that invokes methods of EJB bean. So
the client can be web tier components such as servlet and JSP, which is
typically the case. The client can be standalone application or applet
running within a browser. It can be even another EJB. In fact, as we will
talk about it later on, session beans and entity beans are used together in so
called facade pattern in which session beans receive client requests and then
talk to entity beans for data access logic. So in this case, the session beans
are playing the client role to the entity beans.

EJB 2.1 specification also talks about how business functions of EJB can
be exposed as web services. So in this case, the client can be web services
client invoking the methods of EJB bean by sending and receiving SOAP
messages.

So basically the client model provides development model for clients using
EJB services, that is, how to invoke business methods of EJB bean.

24
06/01/2003

Client View Contract (Contd.)


? Client view contract is comprised of
– Home interface
? For local or remote clients
? Contains methods for creating and locating beans
– Remote interface
? For local or remote clients
?
Contains business methods
– Object identity
– Metadata interface
– Handle
25

So client view contract is comprised of so called interfaces - home interface


and remote interface. We will talk about these home interface and remote
interface several times today. Basically home interface and remote interface
are Java interface types that define the common view of the functionality that
is provided by the EJB bean.

Also there is a concept of object identity that is the identity of a bean


instance. There is metadata interface that a client can use to find out more
information on the bean. And the concept of a handle which is object
reference to the bean from the client perspective.

We will talk about these things in more detail later on.

25
06/01/2003

Component Contract: What


Container does (for Beans)
? Enables EJB method invocations from clients
? Manage the life cycle of EJB bean instances
? Implements home and remote interfaces
? Provide persistence for CMP entity beans
? Provide runtime context information to beans
? Manage transactions, security, exceptions, etc...
? Implements callbacks

26

Component contract basically specifies what the container is required to do for components.

For example, the container enables the EJB method invocation from clients. As we will talk
about this concept several times today, when a client makes a method invocation, the container
in fact intercepts the call first and do something and then delegate the call eventually to your
bean instance.

Container manages the life-cycle of EJB bean instances. That is, bean developer does not have
worry about creating an instance of the bean, because container handles it. And since the
container knows the best in terms of system resources, it also knows when is the good time to
create a pool of bean instances and when to remove or passivate them.

It is the container that actually implements the home and remote interfaces. And in fact, the
implementation of these interfaces are called EJB home object and EJB object. Again we will
talk about this several times.

Container handles the persistence for CMP entity beans. CMP stands for Container managed
persistence. For CMP entity beans, bean developer does not handle the database access logic
himself. Instead, it will be dealt with by the container.

Container also creates a context when it first creates a bean instance and passes that context to
the bean. Container also provides other system services such as transaction, security, and
exceptions. Container also invokes methods that are defined in the bean.

26
06/01/2003

EJB Contracts

Client
Client view contract Enterprise
bean instances

EJB Component
Container contract

EJB server

27

So this picture shows the two contracts we just talk about. Again, the client
view contract is between client and EJB container and the component
contract is between bean and its container.

27
06/01/2003

Fundamentals of
EJB Architecture
(source: Applied Enterprise JavaBeans written
by Kevin Boone)

28

An EJB is essentially a software component on which method calls can be


made, and which can itself make calls on other components. These calls
may be made over a network; in this sense EJB technology is similar to Java
RMI and CORBA.

However, there are some distinctive features of EJBs which make EJB
development rather different from (and easier than) other techniques for
developing distributed applications. We will talk about these distinctive
features in this segment of the presentation. (source: Applied Enterprise
JavaBeans)

28
06/01/2003

Fundamentals of EJB Architecture


? Client view of an EJB is defined strictly by
interfaces
? EJBs are isolated and supported by an EJB
container
? EJB container provides an illusion of a single
threaded environment
? EJB container manages database transactions
? EJB container manages access and security

source: Applied Enterprise Beans Technology 29

Now let's talk about fundamentals of EJB architecture. Some of these are rehash of what
we just talked in the “EJB architecture” segment of the presentation. But I would like to
emphasize these points again to make sure you get clear conceptual idea.

29
06/01/2003

Fundamentals of EJB Architecture


? Creating and locating EJBs is standardized
? Instance can be pooled for efficiency
? Container manages resources
? There is a standard deployment process

source: Applied Enterprise Beans Technology 30

This is the continuation of the fundamentals of EJB architecture.

30
06/01/2003

Client view of an EJB is defined


strictly by Interfaces
? Clients can call only those methods
exposed by EJB's interfaces
– Factory interface (home interface)
– Business method interface (remote interface)
? These interfaces are collectively referred to as
“client view”
? An interface is a simply specification of
method signatures
– You bean is not an implementation of the
interface source: Applied Enterprise Beans Technology 31

Clients can call only those methods exposed by the EJB’s interfaces. In the EJB Specification,
the interfaces are collectively referred to as the client view.

Each EJB publishes ‘factory’ interfaces and ‘business method’ interfaces. The factory interfaces
expose methods that clients can use to create, locate and remove EJBs of that type. The business
method interfaces define all the methods that clients can call on a specific EJB after it has been
located or created through the factory interface. The term ‘business method’ is a generic term
used to describe any method that a client can call on a specific EJB, and does not have to be
related to ‘business’ in the dictionary sense.

It is important for the developer to understand that anything that makes method calls on an EJB is
a client of that EJB, and interacts with it via its factory and business method interfaces. This
applies even in the case where multiple EJBs interact within the same JVM. Enforcing this model
allows the EJB container – of which, more later – to provide important services transparently. If
we are sure that the EJBs must be in the same JVM, then we can use local home and local
interfaces, rather than remote home and
remote interfaces.

In Java, as in most programming languages, an interface is simply a specification of method


signatures; it does not indicate how the methods are to be implemented. Obviously something has
to implement the interfaces. You may be surprised to learn that in EJB technology the interfaces
are never implemented by a class authored by the developer. They are implemented by proxy
objects generated dynamically by the server vendor’s tools.

31
06/01/2003

EJBs are isolated and supported by


an EJB container
? EJB method calls from client are
intercepted by EJB container before they
are delegated to EJB beans
– Proxy objects (Home object and EJB object) which
are generated by container
? Container encapsulates EJB beans and acts
as its security manager
? Container provides system services to EJB
beans
source: Applied Enterprise Beans Technology 32

Although EJB clients make method calls as if they were directly on the EJB, in fact the
method calls are actually on the EJB container, which delegates to the EJB itself.
The client never calls EJB methods directly, even if the client and the EJB are actually on
the same server, and even in the same JVM. This strategy allows powerful features like
distributed transaction management to be provided transparently, and provides for
pooling of EJB instances to increase efficiency.

The EJB container, and therefore the EJB, is accessible to clients via proxy objects. We
will have much more to say about these objects later. Message-driven EJBs are not called
directly by clients at all, and don’t have container proxies in the same sense. Instead they
are called directly by the container when it receives a message for a queue or topic in
which the EJB has registered an interest.

The container encapsulates the EJB and acts as its security manager. It also provides
general services to the EJB, as we shall see. The notion of the container and its proxies is
illustrated in figure 3.2. It is a moot point whether the proxies are considered to be part of
the container or separate from it; it makes no practical difference to the EJB developer.

Because the methods on the EJB proxies will delegate to methods on the EJB itself, the
proxies must be generated dynamically to match the EJB. The vendor of the EJB server
vendor will provide tools to support this; normally this generation will take place when
the EJB is deployed to the server.

32
06/01/2003

EJB container provides an illusion of


a single threaded environment
? Bean developer does not have to worry
about concurrency control
? Bean developer write bean as if it is used
in a single threaded environment

source: Applied Enterprise Beans Technology 33

The developer of an EJB should not have to be concerned about concurrency and
thread management; in fact, it contravenes the EJB Specification [EJB2.0 24.1.2] for the
developer to include such code to handle these issues. The container ensures that the
EJB is never called re-entrantly, so the developer can code the EJB as if it were used in a
single-threaded environment.

33
06/01/2003

EJB container manages database


transactions
? Container handles both local and
distributed transactions
? Container supports declarative
transactions

source: Applied Enterprise Beans Technology 34

It does this even when the transaction spans multiple servers. There is a mechanism for
specifying the transactional behavior of EJBs outside of program code, although limited
programmatic control of transactions is permissible as well.

34
06/01/2003

EJB container manages access and


security
? Container handles access control
– Which methods are accessible to which roles
– Access control is declaratively specified in
deployment descriptor
– Programmatic access control is allowed
? Container also provide authentication
scheme
– Bean provider should never have to code
authentication procedures
source: Applied Enterprise Beans Technology 35

Security attributes specify which methods on which EJBs are accessible to which groups
of users. No coding is required, although limited programmatic intervention is allowed.
The EJB server must provide a mechanism for end users to identify themselves to the
application (e.g., a ‘log in’ dialog box). The EJB developer should never have to code
authentication procedures.

35
06/01/2003

Creating and locating EJBs is


standardized
? There is a well-defined way for the client
to create new EJBs, or to find existing ones
– Client uses JNDI to get a proxy object (actually a
reference to stub of a EJB Home object)
– Client then calls either create() or find() method
of the Home object to get another proxy object
(actually a reference to stub of a EJB object)
– Clients always deal with proxy objects never
directly with EJB bean instance

source: Applied Enterprise Beans Technology 36

There is a well-defined way for the client to create new EJBs, or to find existing ones. It
does this on the factory interface, which it finds by doing a JNDI lookup on the EJB
name. Having found the interface, the client can call its create() or find() methods to
create or locate new EJB instances. When it does this, it gets a reference to a proxy, not
to the the EJB itself. The client manipulates the proxy exactly as if it were the real EJB,
but the proxy carries out other functions (transaction management, for example) as well
as delegating method calls to the EJB.

36
06/01/2003

Instances can be pooled for


efficiency by Container
? Container may pool bean instances
– Container knows when is the good time to create
and remove bean instances
? When a client asks container to create a
bean via create() method, the container
might return a bean instance from the
pool
? This is all transparent to client

source: Applied Enterprise Beans Technology 37

When a client creates an EJB, it is really creating a ‘conceptual EJB’, not an instance of a
Java class. The EJB container may pool instances of implementation class, and give the
client a reference to an existing instance when the client asks to create an EJB. Allowing
the container to pool instances can lead to enormous gains in efficiency. Again, this is
transparent to the client, but the developer must be aware of the circumstances in which
pooling is permitted.

37
06/01/2003

Container manages external


resources
? External resources include
– Databases
– Enterprise information systems
– Messaging systems
? External resources are shared among EJBs
? Container handles pooling these resources

source: Applied Enterprise Beans Technology 38

EJBs get access to external resources – such as databases and messaging systems –
through the container. The container can pool, share and manage these resources on
behalf of the EJBs, and in a way which is transparent to the EJB developer. In this way
we get all the benefits or a resource sharing scheme, with few of the disadvantages.

38
06/01/2003

There is a Standard Deployment


Process
? EJB specification standardize
– Packaging EJB application
– Deployment descriptor
? Any EJB compliant platform should be able
to deploy any EJB compliant application

source: Applied Enterprise Beans Technology 39

There is a specified, standard way for the EJB to be packaged and transferred to the
server. This process is called deployment. Any EJB server that complies with the EJB
Specification [EJB2.0 23] must be able to accept an EJB packaged in the correct way,
regardless of the platform on which it was developed and tested.

39
06/01/2003

J2EE
Component & Container
Architecture

40

OK, one of the most significant architectural characteristics of J2EE, in my


mind, is its component and container model. So let's talk about it in a bit
more detail.

40
06/01/2003

J2EE Containers & Components


Applet Container Web Container EJB Container

Applet HTTP/ Servlet


HTTPS JSP RMI EJB

J2SE

RMI/IIOP

RMI/IIOP
JavaMail JavaMail

JDBC
JTA

JDBC
JMS
JNDI

JNDI

JTA
JMS
App Client JAF
Container JAF
App HTTP/ J2SE
Client HTTPS
RMI
RMI/IIOP

JDBC
JNDI
JMS

J2SE J2SE

Database
41

This is what I call the J2EE Container & components diagram. As this diagram illustrates,
containers and components are the key concepts of J2EE.

As for the relationship between components and containers, as you might have guessed it, the
components are running within containers. That is, the containers provides the host execution
environments for the components. In this picture, the components are colored in green and the
containers are in purple. The types of components within J2EE environment are
•Client components that are running on client either as a stand-alone or applet
• JSP or servlet as web components running inside web container
•EJB beans as business components running inside EJB container

And you developers are responsible for the implementation of these components. On the other
hand, the containers are provided by the platform vendors. The containers provide runtime
system services such as transaction coordination, persistence management, resource pooling

The containers are also responsible for providing the enterprise APIs, shown in gold, and the
distributed communication protocols, shown in brown.

In a typical multi-tier, thin client enterprise application, most of the development effort will be
focused on building web-tier components at web-tier and enterprise Java beans at EJB tier.

41
06/01/2003

Containers and Components


Containers Components
Handle Handle
l Concurrency l Presentation
l Security l Business Logic
l Availability
l Scalability
l Persistence
l Transaction
l Lifecycle
management
l Management
42

We touched upon the roles of container and components a bit in the previous slide. Now let’s compare the
tasks that are being performed by containers and the ones performed by components side by side. As we
talked about in the previous slide, the platform vendors provide containers while you as application developers
develop your applications in the form of components and deploy them over the containers. As you probably
will notice, many of the tasks that the containers perform are system services that a typical enterprise
application would need.

First., container handles concurrency. That is, it handles concurrent access from multiple clients to your
business component so that you don’t have to deal with it. However, each platform vendor might use different
synchronization schemes to support concurrency. Second, containers provide built-in security framework so
that implementing secure applications can be a matter of configuring some options on authentication and access
control at the time of deployment rather than at the time of code development. Next, availability and scalability.
We mentioned already that platform vendors compete in their implementations especially in the area of
availability and scalability. For example, one J2EE container vendor might provide high availability by
maintaining session state on a persistent storage. Another vendor might choose to implement it in a different
way.

Persistence and transaction can also be handled by the container if you choose to do so. Or you might want to
implement them on your own in your code if more customized behavior is desired. Life-cycle management.
Containers handle the creation and destruction of your component instances according to its own
implementation scheme. Finally management and administration, some vendors might provide better
management tool for managing and administering various resources in the container.

So what do you have to do as developers? Very little really. You handle only presentation and focus majority
of your development effort on building business components.

42
06/01/2003

What the EJB Container does


? Generates concrete class for
– Remote (Local) Home Interface
– Remote (Local) Interface
? Binds Home to Naming service
– Clients can lookup the Home using JNDI
? Creates “free beans” pool.
? Caches recently accessed beans
? Provides JDBC Connection pooling

43

(to be added)

43
06/01/2003

Terminology

44

Now we have used various terms so far and this is a source of some
confusion in terms of understanding the EJB architecture. So let's make
sure we use consistent terms in referring to specific things.

44
06/01/2003

Terminology Confusion
? The term “EJB” is used in many different
context
– Technology, Architecture, Specification,
Implementation, Product, Server, Container
– Bean class
– Bean instance
– EJB module
– EJB application
– EJB proxy objects

45

In many EJB articles, the term EJB is used to refer to many things.

Sometimes, people use the term “EJB” in order to refer to technology


aspect, sometimes architecture, specification, implementation, product,
server or container.

At other times, the term EJB is used to refer to a bit more concrete artifacts
such as bean class, bean instance, EJB module, or EJB application.

Well understanding the differences among these are in fact important to


understand how EJB works.

45
06/01/2003

We will use these terms


? Bean class (or Implementation class)
– Java class that represents a bean
? Bean instance
– Actual bean object instance running within a EJB
container
? EJB modules (or EJB jar file)
– ejb-jar file
? EJB application (or J2EE application)
– *.ear file
– Contains a set of EJB modules and/or *.war files 46

(to be added)

46
06/01/2003

We will use these terms


? Home interface
– Java interface that contains creation/location
methods
? EJB Home object
– Sometimes called factory object
? Remote interface
– Java inteface that contains business methods
? EJB object
– Implemented by the container
? EJB Home object and EJB object are sometimes
called proxy objects 47

(to be added)

47
06/01/2003

Types of Beans

48

48
06/01/2003

Types of Beans
? Session Beans
– Stateful session beans
– Stateless session beans
? Entity Beans
– Bean Managed Persistence (BMP)
– Container Managed Persistence (CMP)
? Message Driven Beans
– JMS
– JAXM
49

(to be added)

49
06/01/2003

Session Beans
? Does work on behalf of a single client
? Is not persistent and hence relatively short
lived
– Is removed when the EJB™ server crashes
? Does not represent data in data store,
although can access/update such data
? Bean class implements
javax.ejb.SessionBean interface

50

A session EJB is a non-persistent object; its lifetime is the duration of a


particular interaction between the client and the EJB.

The client normally creates an EJB, calls methods on it, and then removes it.
If the client fails to remove it, the EJB container will remove it after a certain
period of inactivity.

Session EJBs are subdivided into ‘stateful’ and ‘stateless’ types. A


stateless session EJB is shared amongst a number of clients, while a stateful
session EJB is created for a specific client and not used by any others. The
use of stateless EJBs offers efficiency advantages but, of course, it is not
always possible to use them.

50
06/01/2003

When to Use Session


Beans?
? Use Session beans to model process or control
objects specific to a particular client.
? To model workflow, processes or tasks,
manage activities (make reservation,
purchase...).
? To Coordinate processes between entity beans,
control interactions of beans
? To Move business application logic from Client
to the Server Side
51

(to be added)

51
06/01/2003

2 Types of Session Beans


? Stateless: execute a request and return a
result without saving any client specific
state information
– transient
– temporary piece of business logic needed by a
specific client for a limited time span
? Stateful: maintains client specific state
Stateless Session bean Stateful Session bean

State instance data

52

Stateless session beans model business processes that can be


completed in a one method call.
Stateless session beans do not maintain their state across meth
od calls. Typically, you use stateless beans when the entire tas
k can be performed within a single method call.
Any instance of a stateless session bean can be used at any tim
e by any client.

52
06/01/2003

Examples of Session Beans


? Stateless session beans
– Catalog
? No client specific state needs to be preserved

– Interest calculator
? No client specific state needs to be preserved

? Business logic with no need for database access

? Stateful session beans


– Shopping cart
? Client specific state needs to be preserved

53

(to be added)

53
06/01/2003

Entity Beans
? Provides object view of data in data store
– Its lifetime not related to the duration of
interaction with clients
– Lives as long as data exists in database i.e. Long
lived
– In most cases, synchronized with relational
databases
? Shared access among clients
? Bean class implements
javax.ejb.EntityBean interface
54

Entity EJBs represent persistent objects; their lifetimes are not related to the
duration of interaction with clients. In nearly all cases, entity EJBs are
synchronized with relational databases; this is how persistence is achieved.
Entity EJBs are always shared amongst clients: a client cannot get an entity
EJB to itself. Thus entity EJBs are nearly always used as a scheme for
mapping relational databases into object-oriented applications.

54
06/01/2003

Entity Beans
? Clients normally look up (find) an existing
entity EJB
– Creation means adding a row to a database table
– Finding means finding a row in a existing database
table
– Removing means removing a row from a database
table
? Entity bean instance has unique identifier
called primary key
– Primary key can be any class
55

Whereas a client normally creates a session EJB and removes it after use,
clients normally look up an existing entity EJB. Creation of an entity EJB
corresponds to adding new data items to the application (e.g., adding rows
to database tables).

An important feature of entity EJBs is that they have identity, that is, one can
be distinguished from another. This is implemented by assigning a primary
key to each instance of the EJB, where ‘primary key’ has the same meaning
as it does for database management. Primary keys that identify EJBs can be
of any type, including programmer-defined classes.

55
06/01/2003

Examples of Entity Beans


? Customer
– Customer data has to persist, thus is maintained
in the database
– Customer data has to survive server crash
– Customer data is shared by many clients
– Each customer has unique identification such as
customer number

56

56
06/01/2003

2 Types of Entity Beans


? CMP (Container Managed Persistence)
– Persistence is managed by Container
– Persistence requirements are specified in
deployment descriptor
– Bean developer does not have to worry about
providing persistence logic in his code
? BMP (Bean Managed Persistence)
– Persistence logic code is provided by Bean
developer

57

57
06/01/2003

When to Use CMP vs. BMP?


? CMP entity beans
– With CMP 2.0, there is no reason not to use CMP
– Database independence
– Higher performance
– Easy to develop and deploy
? BMP entity beans
– More programmatic control is desired

58

58
06/01/2003

Session Beans and Entity Beans

Session Beans Entity Beans


?
Represent a business ?
Represent business data
process ? Shared instance for
?
One instance per client multiple clients
? Short-lived: Life of ? Long-lived: as long as
client is life of bean data in database
? Transient ? Persistent
? Doesn’t survive server ? Survive server crashes
crashes ?
Always transactional
? May be transactional

59

59
06/01/2003

Entity and Session Beans—


Typical Architecture

60

The EJB Specification has relatively little about the intended applications of each of the
EJB types. It is possible, and may be sensible, to build an application entirely of
session EJBs, for example. However, the properties of the EJBs types themselves
strongly favor a ‘tiered’ application model, where entity EJBs separate the session EJBs
from the data sources. In such a model entity EJBs act primarily to provide an object-
oriented view of the data, to simplify the development of the session EJBs which will
then contain the bulk of the application logic. This model has a number of advantages,
which are briefly summarized below.

Instances of the implementation classes of both session EJBs and entity EJBs are held
in a pool by the server, but for different reasons. Session EJBs are pooled to support
large client loads; entity EJBs are pooled to support large databases.

Session EJBs interact with the database through an object-oriented representation


provided by entity EJBs. This makes the session EJBs easier to implement and manage,
and de-couples the business logic from the database model.

It simplifies the transaction management model; because session EJB methods can
encompass multiple method calls on multiple entity EJBs, the transaction boundaries
can be defined to be equivalent to session EJB method call boundaries. The EJB
architecture has built-in support for this notion of transaction management. We will
have much more to say about this subject later.

60
06/01/2003

Entity and Session Beans

61

61
06/01/2003

Message-Driven Beans (MDB)


? Acts as a consumer of asynchronous
messages
? Cannot be called directly by clients
– Activated upon message arrival
– No home or remote interface
? Clients interact with MDB by sending
messages to the queues or topics to which
they are listening
? Stateless
62

A message-driven bean acts as a consumer of asynchronous messages; it cannot be


called directly by clients, but is activated by the container when a message arrives.
Clients interact with these EJBs by sending messages to the queues or topics to
which they are listening. Although a message-driven EJB cannot be called directly
by clients, it can call other EJBs itself.

Message-driven EJBs are the only type that do not follow a strict request-response
interaction with clients.

62
06/01/2003

Roles

63

S.

63
06/01/2003

Roles
? Distinct roles in the application
development and deployment life cycle
– EJB Bean Provider (Component provider)
– Application Assembler
– Deployer
– EJB Server Provider
– Container Provider
– System Administrator
– Tool provider
64

Reusable modules make it possible to divide the application development


and deployment process into distinct roles so that different people or
companies can perform different parts of the process.

The first two roles involve purchasing and installing the J2EE product and
tools. Once software is purchased and installed, J2EE components can be
developed by application component providers, assembled by application
assemblers, and deployed by application deployers. In a large organization,
each of these roles might be executed by different individuals or teams. This
division of labor works because each of the earlier roles outputs a portable
file that is the input for a subsequent role. For example, in the application
component development phase, an enterprise bean software developer
delivers EJB JAR files. In the application assembly role, another developer
combines these EJB JAR files into a J2EE application and saves it in an
EAR file. In the application deployment role, a system administrator at the
customer site uses the EAR file to install the J2EE application into a J2EE
server.

The different roles are not always executed by different people. If you work
for a small company, for example, or if you are prototyping a sample
application, you might perform the tasks in every phase.

64
06/01/2003

Lifecycle Illustration
Creation Assembly Deployment
Assembled
Created by J2EE Modules and Augmented J2EE APP
Component Processed
by Application by Deployer
Developer
Assembler

Deploy

J2EE Container

Enterprise
Components

65

So what are the typical steps involved in building J2EE applications?

- The first step is to create all the necessary business and web components. For
example, developers build business logic components such as EJB beans. They might
also get involved in building Java beans or custom tags of JSP pages. UI designers
also create web pages at this stage. One important point here is that you don’t have to
build everything yourself. That is, you might want to purchase 3rd-party, off-the-shelf
business components instead of building your own. After all, that is the whole point of
component technology. Again, this is possible because of the open and standard
based component technologies such as EJB and J2EE.

- Next step is to assemble these business and web components into an application.
This step is performed by an application assembler. His role is basically to create a
package that contains all the necessary components and descriptors that describe
those components.

- Finally this assembled application gets deployed in a operational environment by a


deployer. The role of deployer is to take the application package that was assembled
and then deploy it in a particular operational environment. Typically the deployer will
set or tune configuration parameters of deployment descriptors in order to achieve the
behavioral characteristics that is desired in a particular operational environment.

65
06/01/2003

Example Scenario: Step 1


Vendor A: Bean Provider creates Payroll bean

Payroll

Deployment
Deployment
Descriptor
Descriptor

66

66
06/01/2003

Example Scenario: Step 2


Vendor B: Bean Provider and Application Assembler

Employee

GUI Self
Service

Depends on: Payroll

Deployment
Deployment
Descriptor
Descriptor

67

67
06/01/2003

Example Scenario: Step 3


Deployment in a Target Container HR
Database
EJB Container
Employee

Self
GUI Service
Payroll
Database

Payroll

Deployment
Deployment
Descriptor
Descriptor

68

68
06/01/2003

Anatomy of a EJB Module

69

69
06/01/2003

Contents of EJB Module


? Bean developer creates EJB Modules (EJB-
JAR files)
? A EJB module contains
– Interface classes (must be present)
? Home interface

? Remote interface

– Bean class (must be present)


– Deployment descriptor (must be present)
– Helper classes (present only when needed by Bean
class)
70

(need an update: Sang)


To develop an enterprise bean, you must provide the following files:
•Deployment descriptor: An XML file that specifies information about the bean
such as its persistence type and transaction attributes. The deploytool utility
creates the deployment descriptor when you step through the New Enterprise Bean
wizard.
•Enterprise bean class: Implements the methods defined in the following interfaces.
•Interfaces: The remote and home interfaces are required for remote access. For
local access, the local and local home interfaces are required. (Please note that
these interfaces are not used by message-driven beans.)
•Helper classes: Other classes needed by the enterprise bean class, such as
exception and utility classes.
You package the files in the preceding list into an EJB JAR file, the module that
stores the enterprise bean. An EJB JAR file is portable and may be used for
different applications. To assemble a J2EE application, you package one or more
modules--such as EJB JAR files--into an EAR file, the archive file that holds the
application. When you deploy the EAR file that contains the bean's EJB JAR file,
you also deploy the enterprise bean onto the J2EE server.

70
06/01/2003

Anatomy of EJB Module


(EJB-JAR file)
deployment
descriptor

71

71
06/01/2003

Home Interface
? Defines methods for creating, finding and
removing beans
– Factory interface
? Implemented by Container
– EJB home object
? Client gets “reference to stub object of the
EJB home object” via JNDI
? Can be remote or local

72

72
06/01/2003

Example: (remote) Home interface


package com.kevinboone.ejb_book.interest;
import javax.ejb.*;
import java.rmi.*;

// (Remote) home interface for the `Interest' EJB (c)2002 Kevin Boone
public interface InterestHome extends EJBHome{

//Create an instance of the EJB


public Interest create()
throws CreateException, RemoteException;
}

73

73
06/01/2003

Example: Local Home interface


package com.kevinboone.ejb_book.interest;
import javax.ejb.*;
import java.rmi.*;

// (Local) home interface for the `Interest' EJB (c)2002 Kevin Boone
public interface InterestLocalHome extends EJBLocalHome {

// Create an instance of the EJB


public InterestLocal create()
throws CreateException;
}

74

74
06/01/2003

Home Interface and EJB


Home object

75

75
06/01/2003

Remote Interface
? Defines business methods
– Business methods are methods that deals with
application specific business logic
? Implemented by Container
– EJB object
? Client gets “reference to stub object of the
EJB object” through create() or find()
method of EJB Home interface
? Can be remote or local
76

76
06/01/2003

Remote Interface and EJB


object

77

77
06/01/2003

Example: Remote interface


package com.kevinboone.ejb_book.interest;
import javax.ejb.*;
import java.rmi.*;

// Remote interface for the `Interest' EJB (c)2002 Kevin Boone


public interface Interest extends EJBObject{

// Calculate the interest payable on a certain principal, at a


// specified (percent) interest rate per term, for a specific number of terms
public double getInterestOnPrincipal
(double principal, double interestPerTerm, int terms)
throws RemoteException;

// Calculate the total amount payable on a certain principal,


// at a specified (percent) interest rate per term, for a specific number of terms
public double getTotalRepayment
(double principal, double interestPerTerm, int terms)
throws RemoteException;

78

78
06/01/2003

Example: Local interface


package com.kevinboone.ejb_book.interest;
import javax.ejb.*;
import java.rmi.*;

// Local interface for the `Interest' EJB (c)2002 Kevin Boone


public interface InterestLocal extends EJBLocalObject {

// Calculate the interest payable on a certain principal, at a


// specified interest rate per term, for a specific number of terms
public double getInterestOnPrincipal
(double principal, double interestPerTerm, int terms);

// Calculate the total amount payable on a certain principal,


// at a specified interest rate per term, for a specific number of terms
public double getTotalRepayment
(double principal, double interestPerTerm, int terms);
}

79

79
06/01/2003

Remote & Home Interface

source:J2EE tutorial in java.sun.com 80

80
06/01/2003

How Client invokes


Methods of EJB Bean

81

Now let's go over the steps that client takes in order to invoke a business
method of a bean.

81
06/01/2003

Steps for Client To Invoke


Methods of EJB
1.Get EJB home object (actually a stub object of
the EJB home object) via JDNI
? Get initial context
? Perform lookup
? Perform narrowing
2.From EJB home object, get a EJB object
(actually a stub object of the EJB object)
3.Invoke Business methods through EJB object
4.Clean up
82

To find the EJB’s home object the client first instantiates a JNDI naming context,
using the default constructor. This will work if the defaults used by the naming
service are appropriate for your system. For the J2EE Reference Implementation
the defaults will be correct if the client can contact the server using the hostname
‘localhost’ and the naming service is listening on port 1050. If the client and server
are running on the same machine, this is likely to be the case. Your server vendor’s
documentation should tell you whether the naming context needs additional
information. If the naming service is not running on the same machine as the client
(as is likely in practice), the client needs to supply some more information to JNDI .

The client uses PortableRemoteObject.narrow() to convert the result of the lookup


operation into an RMI stub. The client does not have to use narrow() on the result
of the create() call on the remote interface. In fact the narrow() call will be
embedded inside the create() method, so it is still called, but not explicitly.

The client calls remove() on the remote object when it has finished with the EJB. As
we shall see, however, the server does not remove the bean instance, or call
ejbRemove() on it at this point.

82
06/01/2003

Example: Client (page 1)


package com.kevinboone.ejb_book.interest;
import javax.ejb.*; import javax.naming.*;
import javax.rmi.*;
import java.rmi.*;

// Test client class for the `Interest' EJB (c)2002 Kevin Boone
public class InterestTestClient {
public static void main (String[] args) throws Exception {
// Step 1 and Step 2 are captured in a subroutine called getInterest()
Interest interest = getInterest();
double principal = 10000.0;double rate = 10.0;int terms = 10;
System.out.println ("Principal = $" + principal);
System.out.println ("Rate(%) = " + rate);
System.out.println ("Terms = " + terms);
// Step 3: Invoke business methods
System.out.println ("Interest = $" +
interest.getInterestOnPrincipal (principal, rate, terms));
System.out.println ("Total = $" +
interest.getTotalRepayment( principal, rate, terms));
// Step 4: Clean up, remove instance of stateless session bean
interest.remove(); 83
}

83
06/01/2003

Example: Client (page 2)


// Get an instance of the Interest EJB. Note that the
// EJB-specific stuff is wrapped up in this method,
// so that the main logic can just be plain Java
public static Interest getInterest()
throws CreateException, RemoteException, NamingException {

// Step 1: Get an instance of EJB home object (actually a


// stub object to EJB home object) via JNDI
InitialContext initialContext = new InitialContext();
Object o = initialContext.lookup ("Interest");
InterestHome home = (InterestHome)
PortableRemoteObject.narrow (o, InterestHome.class);

// Step 2: Create a EJB remote object (actually a stub object to EJB


// remote object) through EJB home object
return home.create();
}

84

84
06/01/2003

RMI Communication
Model

85

Now I would like to talk a little bit on RMI communication and how it is
related to EJB.

85
06/01/2003

Distributed Objects
? Collaborating objects reside in different
computers (different VMs)
– client object invokes methods of server object
? There have to be some mechanisms
– passing method signature from client to server
– marshalling parameters from client to server
– unmarsalling received parameters at the server
– marshalling return values from server to client
– unmarshalling received results at the client
86

Given that EJB technology is based on the concept of distributed objects


collaborating with each other, understanding the communication model that are
used by these collaborating objects are important.

Now for any collaborating objects in distributed environment to communicate to


each other, there are a certain set of things that need to be taken care of. Among
those, marshaling and unmarshaling parameters and return values are important
aspect of it.

86
06/01/2003

RMI Communication Model

Remote
Caller Object

Remote Interface

Stub Skeleton

87

So in a typical RMI communication model, in order for the caller and the
remote object to communicate, there has to be something like stub and
skeleton. The stub receives method calls from the caller and then marshals
the parameters and then passes the information on the method and its
parameters to the server side. On the server side, it is the skeleton who
receives the method and parameters. It then unmarshals the parameters and
then passes it to the remote object. Remote object then performs the
business functions of the business method and then return the result. The
skeleton then receives the result and then marshals it and sends it to the
client.

Now in object-oriented environment, the client and server has to have a


common view on what methods are to be invoked in what fashion. That is
the method signatures have to be agreed upon between the caller and the
remote object. That agreement is represented in a remote interface.

87
06/01/2003

RMI Control Flow

88

88
06/01/2003

RMI Control Flow


? Caller (Client)
1. invokes a method of a remote object
? Stub of the remote object
1. intercepts the method call
2. marshals the arguments
3. makes calls to remote object

89

89
06/01/2003

RMI Control Flow


? Remote object
1. Receives the calls via Skeleton
2. Unmarshals the arguments
3. Performs the call locally
4. Marshals the result
5. Send the result to client
? Stub
1. Receives result
2. Unmarshal result
3. Return result to client

90

90
06/01/2003

Where does RMI


Communication occur?

RMI over IIOP


91

91
06/01/2003

Where are Stubs?

stubs

RMI over IIOP


92

92
06/01/2003

EJB™ Home & EJB™ Object


skeletons proxy
interfaces objects
stubs

create, find
EJBHome
Client
glue bean

EJBObject
business
methods
container

server

93

(to be added)

93
06/01/2003

RMI over IIOP

94

A Client makes a request on a remote object using a client-side stub. The stub
marshalls the method arguments into serialized form and forwards the method
request to the Object Request Broker. An Object Request Broker is an
intermediary between distributed objects enabling them to communicate. ORBs
are responsible for finding objects to service methods calls, handling parameter
passing, and returning results. The ORB converts the client request into low-
level transport requests ( IIOP), then the request is sent over the network to the
remote object.

On the Server side the ORB receives the transport level request and converts it
into a request for the server skeleton for the remote object. The skeleton
converts the remote request into the appropriate method call un-marshalling the
method arguments and passing them to the remote object implementation.

94
06/01/2003

RMI over IIOP


? RMI mechanism used between EJB client
and EJB server
– Before EJB 2.0 (J2EE 1.3), RMI over IIOP has to be
used even if EJB client and EJB server reside in the
same VM, which results in unnecessary overhead
– Vendor products provide some optimized
communication if client and server reside in a
single VM
? RMI operations are in general expensive
– Reason why “local interface” are introduced in EJB
2.0 (J2EE 1.3) 95

95
06/01/2003

Local versus Remote


Client View

96

We talked a couple of times already on local and remote interface. Let's


talk about when you want to use local interface and when you want to use
remote interface.

96
06/01/2003

Local Client View


? Local interfaces
? Used when client resides in the same VM
with EJB bean (thus with EJB container)
? No overhead of RMI over IIOP
communication
? Introduced in EJB 2.0 (J2EE 1.3)
? Methods do not have to throw
RemoteException
? “Call by reference” is possible
97

97
06/01/2003

Local Client
? (talk about Local client has to be session
bean talking to local entity beans)

98

98
06/01/2003

Local Interface
? Advantages
– More efficient access due to co-location due to no
RMI over IIOP overhead
– Ability to share data between client and bean
through call by reference
? Disadvantages
– Tight coupling of client and bean
– Less flexibility in distribution
? Use local interface beans (as opposed to
remote beans) for fine-grained operations
99

The most distinguished advantage of local bean is its efficiency. Because it


is located in the same address space as its client, the cost of method
invocation is marginal. And because they are colocated, they can pass the
data as call by reference.

The disadvantage is that the bean is now tightly coupled with its client, thus
there is no flexibility in distribution. That is, the local bean has to be co-
located with its client. So the recommendation is that you can use fine-
grained interfaces for local beans because the cost is very minimum.

99
06/01/2003

Can Local and Remote Interfaces


be used together?
? You can build your bean to support both local
and remote interface at the same time
? EJB client cannot be both, however
– This is compile time decision (rather than runtime
decision)

100

100
06/01/2003

Recommendations
? Use local interface whenever possible
– Create islands of local components (local entity
beans and their dependent objects)
? Use facade pattern in which a remote
interface session bean (for synchronous
operations) or message driven bean (for
asynchronous calls) invokes local entity
beans
? Use remote interface for loose coupling
101

So how do you design your application? In most of the cases, you want to
use local interface whenever possible. That is, you can create island of
local beans.

Then create a remote session bean which functions as a facade to these


local beans. So the remote session bean has coarse-grained methods while
local beans have fine-grained methods. If you have a need to loosely
coupled relationship between a client and its bean, then you might want to
use remote interface.

101
06/01/2003

Remote Session Bean Facade


With a Network of Local Entity Beans
Dependent EJB
objects
Tier

Line Item
Remote Entity
Session Card
1:m
Bean Entity
Facade Purchase
Order Entity

Address
Entity
Relationship
Reference
102

So this picture illustrates the recommended architectural model in which


session bean is used to communicate with client while within the EJB tier,
the communication is via local interface. This provides efficient processing
as well as loose coupling between the client and the backend business
components.

102
06/01/2003

Message Driven Bean Facade With a


Network of Local Entity Beans
Local
EntityBean EJB
Asynchronous Tier
message Local
delivery
EntityBean
Message Local
Driven EntityBean
Bean Local
EntityBean

Local
EntityBean
Relationship
Reference 103

This is the case where message driven beans are used to receive
messages asynchronously and then invoke other beans for business
logic processing.

103
06/01/2003

EJB-JAR Deployment
Descriptor

104

Now let's talk about EJB-JAR deployment descriptor.

104
06/01/2003

EJB-JAR Deployment Descriptor


? Gives the container instructions on how
to manage the enterprise bean
? Allows declarative customization
? Controls behaviors for:
– Transaction
– Security
– Life cycle
– State management
– Persistence
– … 105

105
06/01/2003

EJB-JAR Deployment Descriptor


? Defines contract between producer and
consumer of ejb-jar file
? It is an XML document that must be well
formed in XML sense and must be valid with
respect to the DTD given in EJB specification
? Must be stored with the name META-INF/ejb-
jar.xml in the ejb-jar file
? Captures two basic kinds of information viz.
Structural and Application assembly
information
106

106
06/01/2003

EJB-JAR Deployment Descriptor:


Structural Information
? Describes structural and external
dependencies of enterprise bean
? Mandate on ejb-jar producer to provide
structural information
? Should not be changed since it may break the
enterprise bean's function
? Example
– Fully qualified class name of Enterprise bean class,
home interface and remote interface
– State management type of session bean, etc. 107

107
06/01/2003

EJB-JAR Deployment Descriptor:


Application Assembly Information
? Describes how enterprise bean(s) in ejb-jar file
can be composed into a larger application
deployment unit
? Can be optionally provided by ejb-jar producer
? Changes may not break functionality of
enterprise bean, however doing so may
change its behavior
? Examples
– Transaction attributes
– Re-entrancy indication, etc. 108

108
06/01/2003

Example: Deployment Descriptor of


EJB-JAR file: ejb-jar.xml (page 1)
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'


'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<display-name>Interest_ejb</display-name>
<enterprise-beans>
<session>
<display-name>InterestBean</display-name>
<ejb-name>InterestBean</ejb-name>
<home>com.kevinboone.ejb_book.interest.InterestHome</home>
<remote>com.kevinboone.ejb_book.interest.Interest</remote>
<local-home>com.kevinboone.ejb_book.interest.InterestLocalHome</local-home>
<local>com.kevinboone.ejb_book.interest.InterestLocal</local>
<ejb-class>com.kevinboone.ejb_book.interest.InterestBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
<security-identity>
<description></description>
<use-caller-identity></use-caller-identity>
</security-identity>
</session>
109
</enterprise-beans>

structural information

109
06/01/2003

Example: Deployment Descriptor of


EJB-JAR file: ejb-jar.xml (page 2)
<assembly-descriptor>
<method-permission>
<unchecked />
<method>
<ejb-name>InterestBean</ejb-name>
<method-intf>Remote</method-intf>
<method-name>getHandle</method-name>
<method-params />
</method>
...
</method-permission>
</assembly-descriptor>
</ejb-jar>

110

assembly information

110
06/01/2003

EJB Packaging

111

Now let's talk about how EJB application can be packaged.

111
06/01/2003

Package Files
? J2EE Application (sometimes called EJB
application)
– *.EAR file
– Can contain Web tier modules (*.WAR files) and
EJB-JAR files
? EJB-JAR (EJB Module)
– *.jar file
– Some container allows direct deployment of EJB-
JAR files
? EJB Client Jar
112

112
06/01/2003

*.EAR file
? Contains both Web-tier modules and EJB
Modules (EJB-JAR files)
– It can contain multiple EJB-JAR files
? Has its own deployment descriptor
– application.xml
? For deploying EJB application over J2EE RI, you
have to create *.EAR file even if you have only
one EJB-JAR file and no Web modules
– Some container allows direct deployment of EJB-
JAR
113

113
06/01/2003

Example: Deployment Descriptor of


J2EE Application: application.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE application PUBLIC '-//Sun Microsystems, Inc.//DTD J2EE Application


1.3//EN' 'http://java.sun.com/dtd/application_1_3.dtd'>

<application>
<display-name>interest</display-name>
<description>Application description</description>
<module>
<ejb>ejb-jar-ic.jar</ejb>
</module>
</application>

114

114
06/01/2003

Interest.EAR file structure


? ejb-jar-ic.jar
?
META-INF
– application.xml
– ejb-jar.xml
– sun-j2ee-ri.xml
?
com
– com\kevinboone\ejb_book\interest
? InterestLocal.class

?
InterestLocalHome.class
? InterestBean.class

?
InterestHome.class
? Interest.class

115

115
06/01/2003

EJB-JAR file
? Standard format for packaging enterprise
beans
? Used to package un-assembled and assembled
enterprise beans
? Must contain deployment descriptor
? For each enterprise bean, ejb-jar file must
contain following class files
– Enterprise bean class
– Enterprise bean home and remote interface
– Primary key class if the bean is entity bean
116

EJB-JAR file is a standard format for packaging enterprise beans. You can
package both unassembled and assembled enterprise beans.

It contains deployment descriptor

116
06/01/2003

Ejb-client JAR file


? Ejb-jar file producer can create ejb-client JAR
file for ejb-jar file
? Consists of all classes that client program
needs to use client view of enterprise beans
contained in ejb-jar file
? Can be specified in deployment descriptor of
ejb-jar file
? Deployer should ensure that specified ejb-
client JAR file is accessible to client program's
class loader 117

117
06/01/2003

EJB™ Role: Bean Provider


home remote bean Deployment
interface interface class descriptor

Deployment tools

home
interface
bean
class
remote
interface

Deployment
descriptor
118

118
06/01/2003

EJB™ Role: Application Assembler


ejb-jar (.jar) Web jars (.war):
servlets, JSP…
Deployment
descriptor

Deployment tools

Application Jar (.ear):

119

119
06/01/2003

EJB™ Role: Deployer


Application Jar
Deployment
descriptor

Deployment tools
EJBHome EJBObject
Enterprise Beans
Container

Client stubs
context
meta attributes

client

Database

120

120
06/01/2003

Naming Conventions
For EJB Development

121

Now, since there are many pieces involved in typical EJB development, and
also typically you have more than a few EJB to build a relatively
sophisticated EJB applications, it is a good habit to use consistent names.
So here are the conventions.

121
06/01/2003

Naming Conventions
? Home Interface
– CatalogHome (remote), CatalogLocalHome (local)
? Remote Interface
– Catalog (remote), CatalogLoca (local)
? Bean class
– CatalogBean
? EJB-JAR Deployment Descriptor
– ejb-jar.xml (Same for all Beans)
122

Naming conventions for interfaces are pretty much well-agreed upon. For example,
for home interface, you name it with Home postfix. For example, you use
CatalogHome or CatalogLocalHome. For remote interface, use the name itself.
For example, Catalog or CatalogLocal will do. Bean class is typically named as
name with Bean postfix. An example is CatalogBean.

As for the deployment descriptor, same name ejb-jar.xml is used for all EJBs.
Since this xml file is under bean specific directory having same deployment
descriptor is not a problem.

122
06/01/2003

Naming Conventions (Only a


suggestion)
? EJB-JAR file & display name
– <custom-name>.jar, ex: petstore.jar
– <custom-name>JAR.jar, ex: petstoreJAR.jar
? EJB Application & display name
– <custom-name>.ear, ex: interest.ear
– <custom-name>EAR.ear, ex:interestEAR.ear
? EJB Application deployment descriptor
– application.xml (Same for all apps)
? Container specific deployment descriptor
– <custom-name>.xml, ex: sun-j2ee-ri.xml
123

123
06/01/2003

EJB 2.0 Features

124

I have separate EJB 2.0 section here to introduce new features introduced in
EJB 2.0.

124
06/01/2003

EJB 2.0 New Features


? Integrated support for JMS
? Support for local interfaces
? Improved architecture for Container Managed
Persistence
– Support for container managed relationships among
entity beans
? Enterprise JavaBeansTM Query Language (EJB QL)
? Home methods for entity beans
? Network interoperability
125

125
06/01/2003

EJB and JMS

126

126
06/01/2003

JMS Support
? By adding new enterprise bean type called
"MessageDrivenBean"
– Stateless bean without home and remote
interface
– Activated upon message arrival
– Bean implements javax.jms.MessageListener
interface
– onMessage() method implementation should
contain business logic
– Configured as listener for queue or topic
127

127
06/01/2003

JMS and EJB


? JMS APIs for sending messages available to
all enterprise beans
– Use in point-to-point configurations a.k.a
Reliable Queuing
– Use within pub/sub configurations

128

128
06/01/2003

Home Methods

129

129
06/01/2003

Home Methods
? Additional methods on Home interface for
entity beans with both bean and container
managed persistence
– Business methods that are not specific to an entity
bean instance
– Implementation provided by Bean Provider
– Useful for bulk updates or other aggregate
operations

130

130
06/01/2003

Resources

131

131
06/01/2003

Resources Used
? Applied Enterprise JavaBeans Technology written by Kevin
Boone, Prentice Hall [1]
?
J2EE Tutorial in java.sun.com [2]

132

132
06/01/2003

Live your life


with Passion!

133

133

Vous aimerez peut-être aussi