You are on page 1of 28

1.

INTRODUCTION OF BEANS
1.1 Reusable software component: Reusable components are simply pre-built pieces of programming code designed to perform a specific function. While designing an application in a visual environment, controls can be quickly dropped into the design, and modified to fit the task at hand. Most of the controls you'll find are designed to handle such tasks as pushbuttons, menus, text labels, and so forth. As a developer, you only need to write code to "glue" them into your application, and develop the interactions between controls. Recently, programmers have been searching for some way to create and reuse components in the Java language. Java holds great promise, but the early releases lacked any method for creating reusable controls, and thus caused extended development times for applications. Sun Microsystems, the creators of the Java language, have at last recognized this need, and have released the Java Beans Component Architecture. Java Beans are, quite simply, reusable controls written in Java, for Java application development. Beans are "capsules" of code, each designed for a specific purpose. The advantage of Java Beans over standard programming controls is that Beans are independent. They are not specific to operating systems or development environments. A Bean created in one development environment can be easily copied and modified by another. This allows Java Beans greater flexibility in enterprise computing, as components are easily shared between developers. Reusable software components can be simple like familiar push buttons, text fields list boxes, scrollbars, dialogs, for exampleFigure 1 : Button Beans

Figure 2 : Slider Beans

These are the kinds of component sets, toolkits, or widget libraries traditionally sold by third parties. Lately we've seen vendors selling more complex software components like calendars, and spreadsheets.

Figure 3 : Calendar With Beans, you can purchase custom components for Java from third parties. You can also purchase builder tools or application construction programs supporting Beans that let you build Java applications by visually selecting components from palettes, panels, or menus, and hook up events to event handlers. Components can be nested and arbitrarily complex. For example, a calculator built from components becomes, itself, a component.

Figure 4 : Calculator

2. JAVA BEANS
2.1 Definition JavaBeans is an object-oriented programming interface from Sun Microsystems that lets you build re-useable applications or program building blocks called components that can be deployed in a network on any major operating system platform. Like Java applets, JavaBeans components (or "Beans") can be used to give World Wide Web pages (or other applications) interactive capabilities such as computing interest rates or varying page content based on user or browser characteristics. 2.2 Beans or Class Libraries It's logical to wonder: "What is the difference between a Java Bean and an instance of a normal Java class?" What differentiates Beans from typical Java classes is introspection. Tools that recognize predefined patterns in method signatures and class definitions can "look inside" a Bean to determine its properties and behaviour. A Bean's state can be manipulated at the time it is being assembled as a part within a larger application. The application assembly is referred to as design time in contrast to run time. In order for this scheme to work, method signatures within Beans must follow a certain pattern in order for introspection tools to recognize how Beans can be manipulated, both at design time, and run time. In effect, Beans publish their attributes and behaviours through special method signature patterns that are recognized by beans-aware application construction tools. However, you need not have one of these construction tools in order to build or test your beans. The pattern signatures are designed to be easily recognized by human readers as well as builder tools. One of the first things you'll learn when building beans is how to recognize and construct methods that adhere to these patterns. Not all useful software modules should be Beans. Beans are best suited to software components intended to be visually manipulated within builder tools. Some functionality, however, is still best provided through a programatic (textual) interface, rather than a visual manipulation interface. For example, an SQL, or JDBC API would probably be better suited to packaging through a class library, rather than a Bean. 2.3 Application builder tool The primary purpose of beans is to enable the visual construction of applications. You've probably used or seen applications like Visual Basic, Visual Age, or Delphi. These tools are referred to as visual application builders, or builder tools for short.Example- Bean Development Kit, Netscape etc.

2.4 Basic bean concepts Individual Java Beans will vary in functionality, but most share certain common defining features.

Support for introspection allowing a builder tool to analyze how a bean works. Support for customization allowing a user to alter the appearance and behaviour of a bean. Support for events allowing beans to fire events, and informing builder tools about both the events they can fire and the events they can handle. Support for properties allowing beans to be manipulated programatically, as well as to support the customization mentioned above. Support for persistence allowing beans that have been customized in an application builder to have their state saved and restored. Typically persistence is used with an application builder's save and load menu commands to restore any work that has gone into constructing an application.

2.5 JavaBean Example PersonBean.java: package beans; /** * Class <code>PersonBean</code>. */ public class PersonBean implements java.io.Serializable { private String name; private boolean deceased; /** No-arg constructor (takes no arguments). */ public PersonBean() { } /** * Property <code>name</code> (note capitalization) readable/writable. */ public String getName() { return this.name; } /** * Setter for property <code>name</code>. * @param name 4

*/ public void setName(final String name) { this.name = name; } /** * Getter for property "deceased" * Different syntax for a boolean field (is vs. get) */ public boolean isDeceased() { return this.deceased; } /** * Setter for property <code>deceased</code>. * @param deceased */ public void setDeceased(final boolean deceased) { this.deceased = deceased; } } TestPersonBean.java: import beans.PersonBean; /** * Class <code>TestPersonBean</code>. */ public class TestPersonBean { /** * Tester method <code>main</code> for class <code>PersonBean</code>. * @param args */ public static void main(String[] args) { PersonBean person = new PersonBean(); person.setName("Bob"); person.setDeceased(false); // Output: "Bob [alive]" System.out.print(person.getName()); System.out.println(person.isDeceased() ? " [deceased]" : " [alive]"); } }

testPersonBean.jsp; <% // Use of PersonBean in a JSP. %> <jsp:useBean id="person" class="beans.PersonBean" scope="page"/> <jsp:setProperty name="person" property="*"/> <html> <body> Name: <jsp:getProperty name="person" property="name"/><br/> Deceased? <jsp:getProperty name="person" property="deceased"/><br/> <br/> <form name="beanTest" method="POST" action="testPersonBean.jsp"> Enter a name: <input type="text" name="name" size="50"><br/> Choose an option: <select name="deceased"> <option value="false">Alive</option> <option value="true">Dead</option> </select> <input type="submit" value="Test the Bean"> </form> </body> </html>

Figure 5 : Java bean

2.6 Local activation The basic run-time model for Java Bean components is that they run within the same address space as their container. So for example, if the container is a Java application, then the contained bean is run in the same Java virtual machine as its container. If the container is a non-Java application, then the Java Bean will run in a Java virtual machine that is directly associated with the application. (Normally this virtual machine will be running in the same address space as the application.)

J
Java Bean

Database Protocol

Database Server

D B C
IIOP Java Bean

CORBA Server

Java Bean

RMI

Java Server

Java Bean Application Figure 6 : Java Bean 2.7 Security Issues Java Beans are subject to the standard Java security model. We have neither extended nor relaxed the standard Java security model for Java Beans. Specifically, when a Java Bean runs as part of an untrusted applet then it will be subject to the standard applet security restrictions and wont be allowed to read or write arbitrary files, or to connect to arbitrary network hosts. However when a Java Bean runs as part of a stand-alone Java application, or as part of a trusted (signed) applet, then it will be treated as a normal Java application and allowed normal access to files and network hosts. In general we advise Java Bean developers to design their beans so that they can be run as part of untrusted applets. 7

The main areas where this shows up in the beans APIs are: Introspection. Bean developers should assume that they have unlimited access to the high level Introspection APIs (Section 8) and the low-level reflection APIs in the design-time environment, but more limited access in the run-time environment. For example, the standard JDK security manager will allow trusted applications access to even private field and methods, but will allow untrusted applets access to only public fields and methods. (This shouldnt be too constraining - the high-level Introspection APIs only expose public information anyway.) Persistence. Beans should expect to be serialized or deserialized in both the design-time and the run-time environments. However in the run-time environment, the bean should expect the serialization stream to be created and controlled by their parent application and should not assume that they can control where serialized data is read from or written to. Thus a browser might use serialization to read in the initial state for an untrusted applet, but the applet should not assume that it can access random files. GUI Merging. In general untrusted applets will not be permitted to perform any kind of GUI merging with their parent application. So for example, menubar merging might occur between nested beans inside an untrusted applet, but the top level menubar for the untrusted applet will be kept separate from the browsers menubar. 2.8 Advantages of Java Beans A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer:

A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a Bean can be saved in persistent storage and restored at a later time. A Bean may register to receive events from other objects and can generate events that are sent to other objects.

3. EJB TECHNOLOGY OVERVIEW


3.1 Need for EJB There are some core problems in Enterprise Level Application development that JSPs/Servlets do not address. By considering the four main problems of Enterprise Application Development: Object Distribution Persistence Transactions Security The problem of Object Distribution In order for an enterprise application to address the issues of scalability, performance and reliability, it is important to distribute the application over different machines, operating systems and operating system processes. It is also important to implement a logically layered system on different physical layers. This allows a set of distributed objects to be accessed from independently developed systems provided they have common interfaces that are network compatible. Object Persistence The industry standard is to store information in a Relational Database, a technology that has been used very successfully for a number of years and very well understood. Unfortunately, Relational Databases and Object Oriented Programming techniques do not go very well together. Relational databases have limited modelling capabilities, problems between the semantics of SQL and Java and it also requires the system to work in two spaces the Java object space and the data space in the Relational database. Transactions Handling transactions within one database is fairly straightforward but for the programs that have to deal with multiple databases, even seasoned programmers start experiencing difficulties. This problem has been solved in the past by Transaction Monitors like IBMs CICS. It has become important to have an inherent support for distributed transactions in Enterprise Applications rather than relying on external systems. Security Authentication and authorization are recurring problems that come up all the time in Enterprise Application Development. RMI lacks any security related provisions and ORB vendors rarely implement CORBA security.

3.2 Introduction The Enterprise JavaBeans (EJB) specification defines an architecture for the development and deployment of transactional, distributed object applications-based,server-side software components. Organizations can build their own components or purchase components from thirdparty vendors. These server-side components, called enterprise beans, are distributed objects that 9

are hosted in Enterprise JavaBean containers and provide remote services for clients distributed throughout the network. 3.3 Design Goals The server-side environment and the tools needed to service it have greatly influenced the design goals for EJB technology. One key design goal was to reduce (as much as possible) the process of building distributed applications. This goal has been accomplished by turning features that ordinarily would need to be hand-coded into simple declarative properties of the enterprise Beans. These declarative properties generate a significant increase in development efficiency because certain behaviors, like security and transactions, are set, not in code, but are "flags" on the Bean itself. This design feature is another way in which EJB technology allows the developer to focus solely on writing business logic. The EJB specification creates an infrastructure that takes care of the system-level programming, such as transactions, security, threading, naming, object-life cycle, resource pooling, remote access, and persistence. It also simplifies access to existing applications, and provides a uniform application development model for tool creation and use. 3.4 Two-tier and three-tier environments In two-tier client-server environments, programmers write applications that are closely tied to vendor-specific software. Typically, two-tier applications access database services or transaction services directly from the client. Such applications are sometimes called fat clients because the application logic resides on the client, making the clients large and complex. This is depicted by the following diagram:

Application

Network

Database Server

Figure 7 : Two Tier computing Environments Three-tier client-server applications employ an intermediary, or middle-tier, application server, which operates between client applications and the back-end databases. The middle tier houses the business logic of the system and coordinates the interaction of the presentation on the client with the back-end databases. 10

There are two fundamental motivations for using a three-tier architecture over a two-tier model: * Improved scalability, availability, and performance * Improved flexibility and extensibility of business systems Two-tier systems perform well by leveraging the processing power of the client, but the dedicated nature of many clients to a single back-end resource, like a database, produces a bottleneck that inhibits scalability, availability, and performance as client populations grow large. Three-tier systems attempt to mitigate this bottleneck by managing back-end resources more effectively. This is accomplished through resource management techniques like pooling and clustering of middle-tier servers. Pooling makes three-tier systems more effective by allowing many clients to share scarce resources like database connections, which reduces the workload on back-end servers. Clustering makes three-tier systems more available and scalable because multiple servers and resources can support fail-over and balance the loads of a growing client population.Three-tier systems are more flexible and extensible than their two-tier counterparts because the business logic and services, such as security and transactions, reside on the middletier and are largely hidden from the client applications. If properly implemented, as is the case with Enterprise JavaBeans, services are applied automatically to client requests and are therefore invisible. Because services are not visible to the client, changes to services are also invisible. Changes and enhancements to business logic on the middle tier can also be hidden from client applications if implemented correctly. Additionally, when clients and middleware components are implemented in the Java programming language, there is a tremendous potential for portability. The class files that implement the clients as well as the application servers can be relocated quite easily to the hosts that are currently most appropriate. As the object-oriented programming paradigm has grown in popularity, distributed-object systems have thrived. Several distributed-object technologies now exist. The most popular are CORBA, created by the Object Management Group, Java RMI (JRMP) from Sun Microsystems, and DCOM and MTS (a.k.a. COM+) from Microsoft. Each has its strengths and weaknesses. Enterprise JavaBeans(EJB) from Sun Microsystems is the most recent addition to this mix and in some regards, it's both a competitor and a partner in these technologies. CORBA (Common Object Request Broker Architecture) went a long way toward addressing vendor lock-in issues in three-tier computing as did other open standards like LDAP. Unfortunately, while CORBA has revolutionized distributed computing, the programming model proved too complex and the vendor adherence to the specification unbalanced. CORBA has advanced distributed computing, but has proven too difficult to implement and less portable than expected. Enterprise JavaBeans (EJB) is Sun Microsystems' solution to the portability and complexity of CORBA. EJB introduces a much simpler programming model than CORBA, allowing developers to create portable distributed components called enterprise beans. The EJB 11

programming model allows developers to create secure, transactional, and persistent business objects (enterprise beans) using a very simple programming model and declarative attributes. Unlike CORBA, facilities such as access control (authorization security) and transaction management are extremely simple to program. Where CORBA requires the use of complex APIs to utilize these services, EJB applies these services to the enterprise bean automatically according to declarations made in a kind of property file called a deployment descriptor. This model ensures that bean developers can focus on writing business logic while the container manages the more complex but necessary operations automatically. Portability in EJB works because the EJB specification mandates a well-defined set of contracts between the EJB container (the vendor's server) and the EJB component (the Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Enterprise JavaBeans business object). These contracts or rules state exactly what services a container must make available to an enterprise bean and what APIs and declarative attributes the bean developer needs to create an enterprise bean. The life cycle of an enterprise bean is specified in detail, so the vendor knows how to manage the bean at run time and the bean developer knows exactly what an enterprise bean can do at any moment in its existence. Enterprise JavaBeans simplifies the development, deployment, and access to distributed objects. The developer of an EJB distributed object, an enterprise bean, simply implements the object according to the conventions and protocol established for Enterprise JavaBeans. EJB-capable application servers may, and do, use any distributed network protocol including the native Java RMI protocol (JRMP), proprietary protocols, or CORBA's network protocol(IIOP). Regardless of the underlying network protocol used in a particular product, EJB uses the same programming API and semantics to access distributed objects as Java RMI-IIOP.The details of the protocol are hidden from the application and bean developer; the mechanics of locating and using distributed beans are the same for all vendors. Note: An enterprise bean is not the same as a JavaBean. A JavaBean is developed using the java.beans package, which is part of the Java 2 Standard Edition. JavaBeans are components that run on one machine, within a single address space. JavaBeans are process components. An enterprise bean is developed using the javax.ejb package, a standard JDK extension, which is a part of the Java 2 Enterprise Edition. Enterprise beans are components that run on multiple machines, across several address spaces. Enterprise beans are thus interprocess components. JavaBeans are typically used as GUI widgets, while enterprise beans are used as distributed business objects. 3.5 The EJB specification The Enterprise JavaBeans specification defines an architecture for a transactional, distributed object system based on components. The specification mandates a programming model, that is, conventions or protocols and a set of classes and interfaces that make up the EJB API. The EJB programming model provides bean developers and EJB server vendors with a set of contracts that defines a common platform for development. The goal of these contracts is to ensure portability across vendors while supporting a rich set of functionality.

12

Figure 8 : 3-Tier EJB Architecture 3.5.1 The EBJ container Enterprise beans are software components that run in a special environment called an EJB container. The container hosts and manages an enterprise bean in the same manner that the java Web server hosts a servlet or an HTML browser hosts a Java applet. An enterprise bean cannot function outside of an EJB container. The EJB container manages every aspect of an enterprise bean at run time including remote access to the bean, security, persistence, transactions, concurrency, and access to and pooling of resources. The container isolates the enterprise bean from direct access by client applications. When a client application invokes a remote method on an enterprise bean, the container first intercepts the invocation to ensure persistence, transactions, and security are applied properly to every operation a client performs on the bean. The container manages security, transactions, and persistence automatically for the bean, so the bean developer doesn't have to write this type of logic into the bean code itself. The enterprise bean developer can focus on encapsulating business rules, while the container takes care of everything else. Containers will manage many beans simultaneously in the same fashion that the Java WebServer manages many servlets. To reduce memory consumption and processing, containers pool resources and manage the life cycles of all the beans very carefully. When a bean is not being used, a container will place it in a pool to be reused by another client, or possibly evict it from memory and only bring it back when it's needed. Because client applications don't have direct access to the beans -- the container lies between the client and bean -- the client application is completely unaware of the container's resource management activities. A bean that is not in use, for example, might be evicted from memory on the server, while its remote reference on the client remains intact. When the client invokes a method on the remote reference, the container simply re-incarnates the bean to service the request. The client application is unaware of the entire process. Figure 9: 13

An enterprise bean depends on the container for everything it needs. If an enterprise bean needs to access a JDBC connection or another enterprise bean, it does so through the container; if an enterprise bean needs to access the identity of its caller, obtain a reference to itself, or access properties it does so through the container. The enterprise bean interacts with its container through one of three mechanisms: callback methods, the EJBContext interface, or JNDI. * Callback Methods: Every bean implements a subtype of the EnterpriseBean interface which defines several methods, called callback methods. Each callback method alerts the bean of a different event in its lifecycle and the container will invoke these methods to notify the bean when it's about to pool the bean, persist its state to the database, end a transaction, remove the bean from memory, and so on. The callback methods give the bean a chance to do some housework immediately before or after some event. * EJBContext: Every bean obtains an EJBContext object, which is a reference directly to the container. The EJBContext interface provides methods for interacting with the container so that that bean can request information about its environment, like the identity of its client or the status of a transaction, or can obtain remote references to itself. * Java Naming and Directory Interface (JNDI): JNDI is a standard extension to the Java platform for accessing naming systems like LDAP, NetWare, file systems, etc. Every bean automatically has access to a special naming system called the Environment Naming Context (ENC). The ENC is managed by the container and accessed by beans using JNDI. The JNDI ENC allows a bean to access resources like JDBC connections, other enterprise beans, and properties specific to that bean. Portability is central to the value that EJB brings to the table. Portability ensures that a bean developed for one container can be migrated to another if another brand offers more performance, features, or savings. Portability also means that the bean developer's skills can be leveraged across several EJB container brands, providing organizations and developers with better opportunities. 14

In addition to portability, the simplicity of the EJB programming model makes EJB valuable. Because the container takes care of managing complex tasks like security, transactions, persistence, concurrency and resource management the bean developer is free to focus attention on business rules and a very simple programming model. A simple programming model means that beans can be developed faster without requiring a Ph.D. in distributed objects, transactions and other enterprise systems. EJB brings transaction processing and distributed objects development into the mainstream. 3.5.2 Enterprise beans To create an EJB server-side component, an enterprise bean developer provides two interfaces that define a bean's business methods, plus the actual bean implementation class. The client then uses a bean's public interfaces to create, manipulate, and remove beans from the EJB server. The implementation class, to be called the bean class, is instantiated at run time and becomes a distributed object. Enterprise beans live in an EJB container and are accessed by client applications over the network through their remote and home interfaces. The remote and home interfaces expose the capabilities of the bean and provide all the methods needed to create, update, interact with, and delete the bean. A bean is a server-side component that represents a business concept like a Customer or a HotelClerk.

Figure 10 3.5.2.1 Remote and home interfaces 15

The remote and home interfaces represent the bean, but the container insulates the beans from direct access from client applications. Every time a bean is requested, created, or deleted, the container manages the whole process. The home interface represents the life-cycle methods of the component (create, destroy, find) while the remote interface represents the business method of the bean. The remote and home interfaces extend the javax.ejb.EJBObject and javax.ejb.EJBHome interfaces respectively. These EJB interface types define a standard set of utility methods and provide common base types for all remote and home interfaces.

Figure 11 The remote interface defines the business methods of a bean, the methods that are specific to the business concept it represents. Remote interfaces are subclassed from the javax.ejb.EJBObject interface, which is a subclass of the java.rmi.Remote interface.

3.5.2.2 Enterprise beans as distributed objects 16

The remote and home interfaces are types of Java RMI Remote interfaces. The java.rmi.Remote interface is used by distributed objects to represent the bean in a different address space (process or machine). An enterprise bean is a distributed object. That means that the bean class is instantiated and lives in the container, but it can be accessed by applications that live in other address spaces. To make an object instance in one address space available in another requires a little trick involving network sockets. To make the trick work, wrap the instance in a special object called a skeleton that has a network connection to another special object called a stub. The stub implements the remote interface so it looks like a business object. But the stub doesn't contain business logic; it holds a network socket connection to the skeleton. Every time a business method is invoked on the stub's remote interface, the stub sends a network message to the skeleton telling it which method was invoked. When the skeleton receives a network message from the stub, it identifies the method invoked and the arguments, and then invokes the corresponding method on the actual instance. The instance executes the business method and returns the result to the skeleton, which sends it to the stub. The diagram below illustrates this concept:

Figure 12 The stub returns the result to the application that invoked its remote interface method. From the perspective of the application using the stub, it looks like the stub does the work locally. Actually, the stub is just a dumb network object that sends the requests across the network to the skeleton, which in turn invokes the method on the actual instance. The instance does all the work; the stub and skeleton just pass the method identity and arguments back and forth across the network. In EJB, the skeletons for the remote and home interfaces are implemented by the container, not the bean class. This is to ensure that every method invoked on these reference types by a client application are first handled by the container and then delegated to the bean instance. The container must intercept these requests intended for the bean so that it can apply persistence (entity beans), transactions, and access control automatically. 17

Distributed object protocols define the format of network messages sent between address spaces. Distributed object protocols get pretty complicated, but luckily you don't see any of it because it's handled automatically. Most EJB servers support either the Java Remote Method Protocol (JRMP) or CORBA's Internet Inter-ORB Protocol (IIOP). The bean and application programmer only see the bean class and its remote interface; the details of the network communication are hidden. With respect to the EJB API, the programmer doesn't care whether the EJB server uses JRMP or IIOP -- the API is the same. The EJB specification requires that you use a specialized version of the Java RMI API, when working with a bean remotely. Java RMI is an API for accessing distributed objects and is somewhat protocol agnostic -- in the same way that JDBC is database agnostic. So, an EJB server can support JRMP or IIOP, but the bean and application developer always uses the same Java RMI API. In order for the EJB server to have the option of supporting IIOP, a specialized version of Java RMI, called Java RMI-IIOP was developed. Java RMI-IIOP uses IIOP as the protocol and the Java RMI API. EJB servers don't have to use IIOP, but they do have to respect Java RMI-IIOP restrictions, so EJB 1.1 uses the specialized Java RMI-IIOP conventions and types, but the underlying protocol can be anything.

3.6 Types of beans There are two basic types of enterprise beans: entity beans, which represent data in a database, and session beans, which represent processes or act as agents performing tasks. As you build an EJB application you will create many enterprise beans, each representing a different business concept. Each business concept will be manifested as either an entity bean or a session bean. You will choose which type of bean a business concept becomes based on how it is intended to be used.
Entity Bean Session Bean Message Driven Bean

Table 1: Types of Beans

18

3.6.1 Entity Bean

Figure 13 : Entity Bean

Entity beans deal with data. They typically represent nouns, such as a frequent flier account, customer, or payment. Plain old Java objects come into existence when they are created in a program. When the program terminates, the object is lost. But an entity bean stays around until it is deleted. A program can create an entity bean and then the program can be stopped and restarted--but the entity bean will continue to exist. After being restarted, the program can again find the entity bean it was working with and continue using it. Plain old Java objects are used only by one program. An entity bean, on the other hand, can be used by any program on the network. Client programs just need to find the entity bean via JNDI in order to use it. Entity beans must have a unique primary key that is used to find the specific entity bean they want to manipulate. For example, an "employee" entity bean may use the employee's social security number as its primary key. Methods of an entity bean run on a "server" machine. When a client program calls an entity bean's method, the client program's thread stops executing and control passes over to the server. When the method returns from the server, the local thread resumes execution.

19

Container-Managed Persistence The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. In short, your entity beans are more portable. 3.6.2 Session Bean

Figure 14 : Session Bean A session bean represents a single client inside the J2EE server. To access an application that is deployed on the server, the client invokes the session bean's methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared--it may have just one client, in the same way that an interactive session may have just one user. Like an interactive session, a session bean is not persistent. (That is, its data is not saved to a database.) When the client terminates, its session bean appears to terminate and is no longer associated with the client.

3.6.2.1 State Management Modes There are two types of session beans: stateful and stateless. 20

Stateful Session Beans

The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts ("talks") with its bean, this state is often called the conversational state. The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state. Stateless Session Beans

A stateless session bean does not maintain a conversational state for a particular client. When a client invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the duration of the invocation. When the method is finished, the state is no longer retained. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients. At times, the EJB container may write a stateful session bean to secondary storage. However, stateless session beans are never written to secondary storage. Therefore, stateless beans may offer better performance than stateful beans.

3.6.2.2 When to Use Session Beans In general, you should use a session bean if the following circumstances hold:

At any given time, only one client has access to the bean instance. The state of the bean is not persistent, existing only for a short period of time (perhaps a few hours).

Stateful session beans are appropriate if any of the following conditions are true:

The bean's state represents the interaction between the bean and a specific client. The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Behind the scenes, the bean manages the work flow of several enterprise beans.

21

To improve performance, you might choose a stateless session bean if it has any of these traits:

The bean's state has no data for a specific client. In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an e-mail that confirms an online order. The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month.

3.6.3 Message Driven Beans A Message-driven EJB is very similar in concept to a Session EJB, but is only activated when an asynchronous message arrives.

Figure 15 : Message Driven Bean 3.7 Deploying EJB technology As mentioned previously, the container handles persistence, transactions, concurrency, and access control automatically for the enterprise beans. The EJB specification describes a declarative mechanism for how these things will be handled, through the use of an XML deployment descriptor. When a bean is deployed into a container, the container reads the deployment descriptor to find out how transaction, persistence (entity beans), and access control should be handled. The person deploying the bean will use this information and specify additional information to hook the bean up to these facilities at run time. A deployment descriptor has a predefined format that all EJB-compliant beans must use and all EJB-compliant servers must know how to read. This format is specified in an XML Document Type Definition, or DTD. The deployment descriptor describes the type of bean (session or 22

entity) and the classes used for the remote, home, and bean class. It also specifies the transactional attributes of every method in the bean, which security roles can access each method (access control), and whether persistence in the entity beans is handled automatically or is performed by the bean. 3.8 Developer Roles EJB Technology divides naturally into five developer roles: server provider, container provider, Enterprise Beans provider, application assemblers, and deployers. Each is described below:

Server providers are specialists in distributed transaction management, dealing with distributed objects, and low-level systems services. Database and TP monitor vendors will typically fill this role. Container providers are generally specialists in systems programming, and might have application-domain experience, because containers have the ability to bridge the EJB environment to existing applications like SAP R/3 and CICS. The container provides the secure, scalable, transactional environment for a Bean, and hence the provider needs experience in these areas. Database and transaction server vendors typically fill this role as well, and provide a standard container. Enterprise Bean providers provide the building blocks for EJB applications. They are typically domain experts who code business logic in the form of Beans. They are not necessarily experts in database or systems programming. They produce an EJB JAR file that contains the components they produce. Object library vendors typically fill this role. Application assemblers are domain experts whose job is to build applications from third party Beans. They may also build a GUI on the client slide. An example of an application assembler is a programmer who builds an application that accesses deployed components. Deployers are usually familiar with an enterprise's operational environment. The deployer takes a packaged application and sets some or all of the application's security and transaction descriptors. The deployer might also use tools to modify the business logic of the Bean.

3.9 Common Uses of EJBs So, given all of this, where would you commonly encounter EJBs and in what roles? Well, the following are some examples:

In a Web-centric application, the EJBs will provide the business logic that sits behind the Web-oriented components, such as servlets and JSPs. If a Web-oriented application requires a high level of scalability or maintainability, use of EJBs can help to deliver this. Thick client applications, such as Swing applications, will use EJBs in a similar way to Web-centric applications. To share business logic in a natural way between different types of client applications, EJBs can be used to house that business logic. Business-to-business (B2B) e-commerce applications can also take advantage of EJBs. Because B2B e-commerce frequently revolves around the integration of business processes, EJBs provide an ideal place to house the business process logic. They can also 23

provide a link between the Web technologies frequently used to deliver B2B and the business systems behind. Enterprise Application Integration (EAI) applications can incorporate EJBs to house processing and mapping between different applications. Again, this is an encapsulation of the business logic that is needed when transferring data between applications (in this case, in-house applications).

3.10 Advantages of EJB EJB provide developers architectural independence EJB insulates developers from the underlying middleware, since the only environment an EJB developer sees is the Java environment. It also helps the EJB server/container vendor to change and make improvements on the underlying middleware layer without affecting a users existing enterprise applications. WORA for server side components Since EJB is based on Java technology, both the developer and the user are guaranteed that their components are Write Once, Run Anywhere (WORA). As long as an EJB Server faithfully conforms to the EJB specification, any EJB application should run within that server. EJB establishes Roles for Application Development The EJB specification assigns specific roles for project participants charged with enterprise application development utilizing EJB.The server vendor can take care of providing support for complex system services and make available an organized framework for a Bean to execute in, without assistance from Bean developers. EJB provides Distributed Transaction support EJB provides transparency for distributed transactions. This means that a client can begin a transaction and then invoke methods on Beans present within two different servers, running on different machines, platforms or JVM. It helps create Portable and Scalable solutions Beans conforming to the EJB API will install and run in a portable fashion on any EJB server. It provides of vendor specific enhancements Since the EJB specification provides a lot of flexibility for the vendors to create their own enhancements, the EJB environment may end being feature rich.

24

3.11 Version Specification of EJB EJB 1.0 (1998-03-24) Announced at JavaOne 1998, Sun's third Java developers conference (March 24 through 27) Goals for Release 1.0:

Defined the distinct EJB Roles that are assumed by the component architecture. Defined the client view of enterprise Beans. Defined the enterprise Bean developers view. Defined the responsibilities of an EJB Container provider and server provider; together these make up a system that supports the deployment and execution of enterprise Beans.

EJB 1.1, final release (1999-12-17) Major changes:


XML deployment descriptors Default JNDI contexts RMI over IIOP Security - role driven, not method driven Entity Bean support - mandatory, not optional

Goals for Release 1.1:


Provide better support for application assembly and deployment. Specify in greater detail the responsibilities of the individual EJB roles.

EJB 2.0, final release (2001-08-22) Major changes: Overall goals:


The standard component architecture for building distributed object-oriented business applications in Java. Make it possible to build distributed applications by combining components developed using tools from different vendors. Make it easy to write (enterprise) 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. Will follow the "Write Once, Run Anywhere" philosophy of Java. An enterprise Bean can be developed once, and then deployed on multiple platforms without recompilation or source code modification. Address the development, deployment, and runtime aspects of an enterprise applications life cycle.

25

Define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime. Be compatible with existing server platforms. Vendors will be able to extend their existing products to support EJBs. Be compatible with other Java APIs. Provide interoperability between enterprise Beans and Java EE components as well as nonJava programming language applications.

EJB 2.1, final release (2003-11-24) Major changes:


Web service support (new): stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference. EJB timer service (new): Event-based mechanism for invoking EJBs at specific times. Message-driven beans accepts messages from sources other than JMS. Message destinations (the same idea as EJB references, resource references, etc.) has been added. EJB query language (EJB-QL) additions: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD. XML schema is used to specify deployment descriptors, replaces DTDs

EJB 3.0, final release (2006-05-11) Major changes: This release made it much easier to write EJBs, using 'annotations' rather than the complex 'deployment descriptors' used in version 2.x. The use of home and remote interfaces and the ejbjar.xml file were also no longer required in this release, having been replaced with a business interface and a bean that implements the interface.

EJB 3.1, final release (2009-12-10) The purpose of the Enterprise JavaBeans 3.1 specification is to further simplify the EJB architecture by reducing its complexity from the developer's point of view, while also adding new functionality in response to the needs of the community:

Local view without interface (No-interface view) EJB Lite: definition of a subset of EJB Portable EJB Global JNDI Names Singletons (Singleton Session Beans) EJB Timer Service Enhancements 26

4. Difference Between Java Bean and EJB


1. JavaBeans may be visible or nonvisible at runtime.For example, the visual GUI component may be a button,list box,graphic or a chart. An EJB is a nonvisual ,remote object. 2. JavaBeans are intended to be local to a single process and are primarly intended to run on the client side.Although one can develop server-side JavaBeans,it is far easier to develop them using the EJB specification instead. EJB's are remotely executable components or business objects that can be deployed only on the server. 3. JavaBeans is a component technology to create generic Java components that can be composed together into applets and applications. Even though EJB is a component technology,it neither builds upon nor extends the original JavaBean specification. 4.JavaBeans have an external interface called the properties interface, which allows a builder tool to interpret the functionality of the bean. EJBs have a dployement descriptor that describes its functionality to an external builder tool or IDE 5.JavaBeans may have BeanInfo classes,property editors or customizers EJB's have no concept of BeanInfo classes,property editors or customizers and provide no additional information other than that described inthe deployment descriptor. 6. JavaBeans are not typed. EJBs are of two types - session beans and entity beans. 7. No explicit support exists for transactions in javaBeans. EJB's may be transactional and the EJB servers provide transactional support. 8. Component bridges are available for JavaBeans.For ex: a javabean can also be deployed as an Activex control. An EJB cannot be deployed as an ActiveX control because ActiveX controls are intended to run at the desktop and EJB's are server side components.However CORBA-IIOP compatibility via the EJB-to-CORBA mapping is defined by the OMG.

5. Conclusion
Enterprise JavaBeans technology presents a new way to develop, deploy and manage distributed business applications. It does this by making it easier for the developer to write business applications as re-usable server components and not have to worry about system-level programming. The Enterprise JavaBeans component architecture represents a giant step forward in simplifying the development deployment and management of enterprise applications. 27

6. References
www.buyya.com/papers/encyclopedia.pdf http://en.wikipedia.org/wiki/JavaBeans http://en.wikipedia.org/wiki/EJB http://java.sun.com/beans http://www.javapassion.com/javase/javabeans.pdf http://www.google.com/http://docs.cs.cf.ac.uk/html/615/node2.html

28

You might also like