Vous êtes sur la page 1sur 30

Master of Computer Application Advanced Java Programming

Unit 1

Introduction to J2EE

J2EE stands for Java 2 Platform Enterprise Edition. It is an Oracle's enterprise Java computing platform.
J2EE is an environment for developing and deploying enterprise applications.
The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for
developing multitier, Web-based applications.
The J2EE platform consists of a set of services, API i.e. application programming interfaces and protocols
which provides the functionality necessary for developing multi-tiered, web-based applications.
It provides a robust development platform upon which to build flexible, reusable components and
The J2EE platform is designed to provide server-side and client-side support for developing distributed,
multitier applications

Features of J2EE

Flexibility & Reliability

Cost Effective
Complete Web services support

MVC Architecture (Figure 1 and Figure 2)

The main aim of the MVC architecture is to separate the business logic and application data from the presentation
data to the user. The main reasons behind the MVC design pattern.

They are reusable: When the problem recurs, there is no need to invent a new solution; we just have to
follow the pattern and adapt it as necessary.
They are expressive: By using the MVC design pattern our application becomes more expressive.

The model: The model is responsible for managing the data of the application. It responds to the request from the
view and it also responds to instructions from the controller to update itself.

The view: A presentation of data in a particular format, triggered by a controller's decision to present the data. They
are script based systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

The controller: The controller is responsible for responding to user input and performs interactions on the data
model objects. The controller receives the input; it validates the input and then performs the business operation that
modifies the state of the data model.

N-Tier Architecture (Figure3, Figure 4 and Figure 5)

Presentation Layer

Static or dynamically generated content rendered by the browser (front-end)

Provides user interface
Handles the interaction with the user
Sometimes called the GUI or client view or front-end
Should not contain business logic or data access code

Logic Layer

Master of Computer Application Advanced Java Programming
A dynamic content processing and generation level application server, e.g., Java EE, ASP.NET, PHP,
ColdFusion platform (middleware)
The set of rules for processing information
Can accommodate many users
Sometimes called middleware/ back-end
Should not contain presentation or data access code

Data Layer

A database, comprising both data sets and the database management system or RDBMS software that
manages and provides access to the data (back-end)
The physical storage layer for data persistence
Manages access to DB or file system
Sometimes called back-end
Should not contain presentation or business logic code


A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web
clients, usually across HTTP, the Hypertext Transfer Protocol.

Interface Servlet: To implement this interface, you can write a generic servlet that extends
javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.

A Generic servlet contains the following methods:

destroy(): Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.

public void destroy()

getServletConfig(): Returns a ServletConfig object, which contains initialization and startup parameters for
this servlet.
getServletInfo(): Returns information about the servlet, such as author, version, and copyright.
Init(): Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

public void init(ServletConfig config) throws ServletException

service(): Called by the servlet container to allow the servlet to respond to a request.

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

doPost(): A POST request results from an HTML form that specifically lists POST as the METHOD and it should
be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


doGet(): A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


Life cycle of Servlet (Figure 6)

Master of Computer Application Advanced Java Programming
Loading and Instantiation: The servlet container loads the servlet during startup or when the first request is
made. After loading of the servlet, the container creates the instances of the servlet.
Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet
initialization parameters to the init() method. The init() method is called only once throughout the life cycle
of the servlet.
Servicing the Request: The servlet container calls the service() method for servicing any request. The
service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for
handling the request and sends response to the client using the methods of the response object.
Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls
the destroy() method . Like the init() method this method is also called only once throughout the life cycle of
the servlet.

Advantages of Java Servlet

Portability: We can develop a servlet on Windows machine running the tomcat server or any other server and later
we can deploy that servlet effortlessly on any other operating system like Unix server running on the Netscape
Application server. So servlets are writing once, run anywhere (WORA) program.

Powerful: We can do several things with the servlets which were difficult or even impossible to do with CGI, for
example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data
among each other, they even make the database connection pools easy to implement.

Efficiency: When the servlet get loaded in the server, it remains in the server's memory as a single object instance.
However with servlets there are N threads but only a single copy of the servlet class.

Safety: As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic
garbage collection and a lack of pointers mean that servlets are generally safe from memory management problems.
In servlets we can easily handle the errors due to Javas exception handling mechanism. If any exception occurs then
it will throw an exception.

Integration: Servlets are tightly integrated with the server.

Extensibility: The servlet API is designed in such a way that it can be easily extensible.

Inexpensive: There are number of free web servers available for personal use or for commercial purpose.


GenericServlet defines a generic, protocol-independent servlet.

GenericServlet gives a blueprint and makes writing servlet easier.
GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the
ServletConfig interface.
GenericServlet implements the log method, declared in the ServletContext interface.
To write a generic servlet, it is sufficient to override the abstract service method.


HttpServlet defines a HTTP protocol specific servlet.

HttpServlet gives a blueprint for Http servlet and makes writing them easier.
HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

Servlet Program (HelloServlet.java)

Master of Computer Application Advanced Java Programming
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException,
PrintWriter pw = response.getWriter();

Session Tracking Techniques

As we know that the Http is a stateless protocol, means that it can't persist the information. It always treats each
request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and
closes the connection. Session Tracking can be done in three ways:

Hidden Form Fields: The hidden form field is sent back to the server when the form is submitted. In hidden
form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that
when you submit the form, the specified name and value will be get included in get or post method.
URL Rewriting: It is used to maintain the session. In session tracking firstly a session object is created when
the first request goes to the server. Then server creates a token which will be used to maintain the session.
The token is transmitted to the client by the response object and gets stored on the client machine.
Cookies: Cookie is nothing but a name- value pair, which is stored on the client machine. When cookie based
session management is used, a token is generated which contains user's information, is sent to the browser
by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the
server is able to identify the user. In this way the session is maintained.


It is an interface which helps us to communicate with the servlet container. There is only one ServletContext for the
entire web application and the components of the web application can share it. The information in the
ServletContext will be common to all the components.

Servlet Collaboration

Sometimes servlets have to cooperate, usually by sharing some information. We call communication of this sort
servlet collaboration. Collaborating servlets can pass the shared information directly from one servlet to another
through method invocations, as shown earlier. This approach requires each servlet to know the other servlets with
which it is collaborating--an unnecessary burden. The collaboration can be done by redirecting a servlet from
another or loading the servlets from the ServletContext access methods. This can also be achieved by the methods
forward() and include() of RequestDispatcher or by sendRedirect() method. There are two main styles of servlet

Sharing information: This involves two or more servlets sharing state or resources.
Sharing control: This involves two or more servlets sharing control of the request.

Master of Computer Application Advanced Java Programming
Unit 2

JSP Architecture

JSP pages are high level extension of servlet and it enables the developers to embed java code in html pages. JSP files
are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.
javax.servlet.jsp package defines two interfaces:


These interfaces define the three methods for the compiled JSP page. These methods are:

_jspService(HttpServletRequest request,HttpServletResponse response)

In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but
the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.

JSP Life Cycle (Figure 7)

A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet
life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed
by a JSP

Compilation: The compilation process involves three steps:

Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests.
Execution: The _jspService() method of a JSP is invoked once per a request and is responsible for generating
the response for that request and this method is also responsible for generating responses to all seven of the
HTTP methods i.e. GET, POST, DELETE etc.
Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets.

JSP Syntax

The Script let: A script let can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.

<% out.println("Your IP address is " + request.getRemoteAddr()); %>

JSP Declarations: A declaration declares one or more variables or methods that you can use in Java code later in the
JSP file. You must declare the variable or method before you use it in the JSP file.

<%! int i = 0; %>

<%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %>

JSP Expression: A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.

Master of Computer Application Advanced Java Programming

Today's date: <%= (new java.util.Date()).toLocaleString()%>

JSP Comments: JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when you want to hide or "comment out" part of your JSP page.

<%-- comment --%>

<!-- comment -->

JSP Directives: A JSP directive affects the overall structure of the servlet class.

<%@ directive attribute="value" %>

The page Directive: The page directive is used to provide instructions to the container that pertain to the
current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives
are coded at the top of the JSP page. List of attributes associated with page directive:
errorPage: Defines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPage: Indicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extends: Specifies a superclass that the generated servlet must extend
import: Specifies a list of packages or classes for use in the JSP as the Java import statement does for
Java classes.
session: Specifies whether or not the JSP page participates in HTTP sessions
<%@ page attribute="value" %>

The include Directive: The include directive is used to includes a file during the translation phase. This
directive tells the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.
<%@ include file="relative url" >

The taglib Directive: The JavaServer Pages API allows you to define custom JSP tags that look like HTML or
XML tags and a tag library is a set of user-defined tags that implement custom behavior. The taglib directive
declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a
means for identifying the custom tags in your JSP page.
<%@ taglib uri="uri" prefix="prefixOfTag" >

JSP Actions: JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the
Java plugin. There are two attributes that are common to all Action elements: the id attribute and the scope

Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced
inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it
through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope
attribute are directly related, as the scope attribute determines the lifespan of the object associated with
the id. The scope attribute has four possible values: (a) page, (b) request, (c) session, and (d) application.

jsp:include: Includes a file at the time the page is requested
<jsp:include page="relative URL" flush="true" />

Master of Computer Application Advanced Java Programming
jsp:useBean: The useBean action is quite versatile. It first searches for an existing object utilizing the id and
scope variables. If an object is not found, it then tries to create the specified object.
<jsp:useBean id="name" class="package.class" />

jsp:setProperty: Sets the property of a JavaBean

jsp:getProperty: Inserts the property of a JavaBean into the output
jsp:forward: Forwards the requester to a new page

<jsp:action_name attribute="value" />

JSP Implicit Objects: JSP supports nine automatically defined variables, which are also called implicit objects.

request: This is the HttpServletRequest object associated with the request.

response: This is the HttpServletResponse object associated with the response to the client.
out: This is the PrintWriter object used to send output to the client.
session: This is the HttpSession object associated with the request.
application: This is the ServletContext object associated with application context.
config: This is the ServletConfig object associated with the page.
pageContext: This encapsulates use of server-specific features like higher performance JspWriters.
page: This is simply a synonym for this, and is used to call the methods defined by the translated servlet
Exception: The Exception object allows the exception data to be accessed by designated JSP.

JSP design strategies (Figure 8 and Figure 9)

Many dozens of design strategies have been developed for web applications. In both cases, the goal is to separate
logic from presentation and to separate as many concerns in the logic as possible

Page-centric: Requests are made to JSPs, and the JSPs respond to clients
Dispatcher: Requests are sent to JSPs or servlets that then forward the requests to another JSP or servlet


The Apache Struts web framework is a free open-source solution for creating Java web application. The framework
provides three key components:

A "request" handler provided by the application developer that is mapped to a standard URI.
A "response" handler that transfers control to another resource which completes the response.
A tag library that helps developers creates interactive form-based applications with server pages.

Master of Computer Application Advanced Java Programming
Struts 1 and Struts 2


Struts1 extends the abstract base class by its While in Struts 2, an Action class implements
action class. The problem with struts1 is that an Action interface, along with other
it uses the abstract classes rather than interfaces use optional and custom services.
Action classes

interfaces. Struts 2 provide a base ActionSupport class

that implements commonly used interfaces.
Although an Action interface is notnecessary,
any POJO object along with an execute
signature can be used as an Struts 2 Action

Struts 1 Actions are singletons therefore they Struts 2 dont have thread-safety issues as
must be thread-safe because only one Action objects are instantiated for each
Threading Model

instance of a class handles all the requests request. A servlet container generates many
for that Action. The singleton strategy throw-away objects per request, and one
restricts to Struts 1 Actions and requires more object does not impose a performance
extra care to make the action resources penalty or impact garbage collection.
thread safe or synchronized while developing
an application.

Actions are dependent on the servlet API Container does not treat the Struts 2 Actions
because HttpServletRequest and as a couple. Servlet contexts are typically
Servlet Dependency

HttpServletResponse is passed to the represented as simple Maps that allow

execute method when an Action is invoked Actions to be tested in isolation. Struts 2
therefore Struts1. Actions can still access the original request
and response, if required. While other
architectural elements directly reduce or
eliminate the need to access the
HttpServetRequest or HttpServletResponse.

Struts1 application has a major problem To test the Struts 2 Actions instantiate the

while testing the application because the Action, set the properties, and invoking
execute method exposes the Servlet API. methods. Dependency Injection also makes
Struts Test Case provides a set of mock testing easier.
object for Struts 1.

Master of Computer Application Advanced Java Programming

Struts 1 receives an input by creating an Struts 2 require Action properties as input

ActionForm object. Like the action classes, all properties that eliminate the need of a
ActionForms class must extend an second input object. These Input properties
Harvesting Input

ActionForm base class. Other JavaBeans may be rich object types, since they may
classes cannot be used as ActionForms, while have their own properties. Developer can
developers create redundant classes to access the Action properties from the web
receive the input. DynaBeans is the best page using the taglibs. Struts 2 also support
alternative to create the conventional the ActionForm pattern, POJO form objects
ActionForm classes. and POJO Actions as well.

Struts1 integrates with JSTL, so it uses the Struts 2 can use JSTL, but the framework also

JSTL EL. The EL has basic object graph supports a more powerful and flexible
traversal, but relatively weak collection and expression language called "Object Graph
indexed property support. Notation Language" (OGNL).

Struts 1 binds object into the page context by Struts 2 use a ValueStack technology to make
Binding values into

using the standard JSP mechanism. the values accessible to the taglibs without
coupling the view to the object to which it is

rendering. The ValueStack strategy enables

us to reuse views across a range of types,
having same property name but different
property types.

Struts 1 ActionForm properties are almost in Struts 2 use OGNL for type conversion and
Type Conversion

the form of Strings. Commons-Beanutils are converters to convert Basic and common
used by used by Struts 1 for type conversion. object types and primitives as well.
Converters are per-class, which are not
configurable per instance.

Struts 1 uses manual validation that is done Struts 2 allows manual validation that is done
via a validate method on the ActionForm, or by using the validate method and the XWork

by using an extension to the Commons Validation framework. The Xwork Validation

Validator. Classes can have different Framework allows chaining of validations
validation contexts for the same class, while into sub-properties using the validations
chaining to validations on sub-objects is not defined for the properties class type and the
allowed. validation context.

Master of Computer Application Advanced Java Programming

Each module in Struts 1 has a separate In Struts 2 different lifecycles are created on
Control Of

Request Processors (lifecycles), while all the a per Action basis via Interceptor Stacks.
Actions in the module must share the same Custom stacks are created and used with
lifecycle. different Actions, as required

Advantages of Struts

Easy to learn and use

Many supported 3rd-party tools
Flexible and extensible
Large user community
Stable and mature
Open source
Integrates well with J2EE
Works with existing web apps
Easy to retain form state
Unified error handling (via ActionError)

Working of Struts

The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts
Java Server Pages (JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which
has been made by the web browsers to the appropriate Server Page. The use of servlet as a router helps to make the
web applications easier to design, create, and maintain. Struts are purely based on the Model- View- Controller
(MVC) design pattern. It is one of the best and most well developed design patterns in use. By using the MVC
architecture we break the processing in three sections named Model, the View, and the Controller basic purpose of
the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts Java Server Pages
(JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which has been made by
the web browsers to the appropriate Server Page. The use of servlet as a router helps to make the web applications
easier to design, create, and maintain. Struts are purely based on the Model- View- Controller (MVC) design pattern.
It is one of the best and most well developed design patterns in use. By using the MVC architecture we break the
processing in three sections named Model, the View, and the Controller.

Master of Computer Application Advanced Java Programming
Unit 4

Session Bean (Figure 11)

A session bean is the enterprise bean that directly interacts with the user and contains the business logic of the
enterprise application. A session bean represents a single client accessing the enterprise application deployed on the
server by invoking its method. An application may contain multiple sessions depending upon the number of users
accessing to the application. A session bean makes an interactive session only for a single client and shields that
client from complexities just by executing the business task on server side.

Stateless Session Beans

A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods
of a stateless bean, the instance of bean variables may contain a state specific to that client only for the duration of a
method invocation. Once the method is finished, the client-specific state should not be retained i.e. the EJB
container destroys a stateless session bean.

Stateful Session Beans

These types of beans use the instance variables that allow the data persistent across method invocation because the
instance variables allow persistence of data across method invocation. The client sets the data to these variables
which he wants to persist. A stateful session bean retains its state across multiple method invocations made by the
same client. If the stateful session bean's state is changed during a method invocation, then that state will be
available to the same client on the following invocation.

Stateful session beans are useful in

What the bean wants to holds information about the client across method invocation.
When the bean works as the mediator between the client and the other component of the application.
When the bean have to manage the work flow of several other enterprise beans.

Stateless session beans are appropriate in

If the bean does not contain the data for a specific client.
If there is only one method invocation among all the clients to perform the generic task.

Life Cycle of Stateless Session Bean (Figure 12)

A stateless session bean starts its life cycle when the client first obtains the reference of the session bean. For this,
the container performs the dependency injection before invoking the annotated @PreConstruct method if any
exists. After invoking the annotated @PreConstruct method the bean will be ready to invoke its method by the
client. The container calls the annotated @PreDestroy method while ending the life cycle of the session bean. After
this, the bean is ready for garbage collection.

Life Cycle of a Stateful Session Bean (Figure 13)

A Stateful session bean starts its life cycle when the client first gets the reference of a stateful session bean. Before
invoking the method annotated @PostConstruct the container performs any dependency injection after this the
bean is ready. The container may deactivate a bean while in ready state. In the passivate mechanism the bean moves
from memory to secondary memory. The container invokes the annotated @PrePassivate method before passivating
the bean. If a client invokes a business method on the passivated bean then the container invokes the annotated
@PostActivate method to let come the bean in the ready state. While ending the life cycle of the bean, the client
calls the annotated @Remove method after this the container calls the annotated @PreDestroy method which
results in the bean to be ready for the garbage collection.

Figure 1 (MVC Architecture)

Figure 2 (MVC Architecture)

Figure 3 (1-tier architecture)

Figure 4 (2-tier architecture)

Figure 5 (3-tier architecture)

Figure 6 (Life cycle of a Servlet)

Figure 7(Life cycle of a JSP page)

Figure 8(Page-centric)
Figure 9(Dispatcher)

Figure 10(Working of Struts)

Figure 11 (Session Bean)

Figure 12 (Life Cycle of Stateless Session Bean)

Figure 13 (Life Cycle of a Stateful Session Bean)


Structure Page Nos.

1.0 Introduction 5
1.1 Objectives 5
1.2 What is JavaBean? 6
1.3 JavaBean Concepts 6
1.4 What is EJB? 9
1.5 EJB Architecture 10
1.6 Basic EJB Example 10
1.7 EJB Types 13
1.7.1 Session Bean 13 Life Cycle of a Stateless Session Bean Life Cycle of a Stateful Session Bean Required Methods in Session Bean The use of a Session Bean
1.7.2 Entity Bean 15 Life Cycle of an Entity Bean Required methods in Entity Bean The Use of the Entity Bean
1.7.3 Message Driven Bean 18 Life Cycle of a Message Driven Bean Method for Message Driven Bean The Use of Message Driven Bean
1.8 Summary 20
1.9 Solutions/Answers 20
1.10 Further Readings/References 24


Software has been evolving at a tremendous speed since its inception. It has gone through
various phases of development from low level language implementation to high level
language implementation to non procedural program models. The designers always make
efforts to make programming easy for users and near to the real world implementation.
Various programming models were made public like procedural programming, modular
programming and non procedural programming model. Apart from these models reusable
component programming model was introduced to put programmers at ease and to utilise
the reusability as its best. Reusable Component model specifications were adopted by
different vendors and they came with their own component model solutions.


After going through this unit, you should be able to:

x define what is Java Beans;

x list EJB types;
x discuss about Java Architecture;
x make differences between different types of Beans;
x discuss the life cycle of a Beans, and
x describe the use of Message Driven Beans.


JavaBeans are software component models. A JavaBean is a general-purpose component

model. A Java Bean is a reusable software component that can be visually manipulated in
builder tools. Their primary goal of a JavaBean is WORA (Write Once Run Anywhere).
JavaBeans should adhere to portability, reusability and interoperability.

JavaBeans will look a plain Java class written with getters and setters methods. 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 Beans 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. For this scheme to work, method signatures within Beans must follow a certain
pattern, for introspection tools to recognise 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 recognised by beans-aware application construction tools. However, you
need not have one of these construction tools in order to build or test your beans. Pattern
signatures are designed to be easily recognised by human readers as well as builder tools.
One of the first things youll learn when building beans is how to recognise 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.


JavaBeans is a complete component model. It supports the standard component

architecture features of properties, events, methods, and persistence. In addition,
JavaBeans provides support for introspection (to allow automatic analysis of a JavaBeans
component) and customisation (to make it easy to configure a JavaBeans component).
Typical unifying features that distinguish a Bean are:

x Introspection: Builder tools discover a Beans features (ie its properties, methods,
and events) by a process known as INTROSPECTION. Beans supports introspection
in two ways:

1) Low Level Introspection (Reflection) + Intermediate Level Introspection (Design

Pattern): Low Level Introspection is accomplished using java.lang.reflect package
API. This API allows Java Objects to discover information about public fields,
constructors, methods and events of loaded classes during program execution i.e., at
Run-Time. Intermediate Level Introspection (Design Pattern) is accomplished using
Design Patterns. Design Patterns are bean features naming conventions to which one
has to adhere while writing code for Beans. java.beans.Introspector class examines
Beans for these design patterns to discover Bean features. The Introspector class relies
on the core reflection API. There are two types of methods namely, accessor
methods and interface methods. Accessor methods are used on properties and are of

two sub-types (namely getter methods and setters methods). Interface methods are Introduction to
Java Beans
often used to support event handling.

2) Higest Level or Explicit Introspection (BeanInfo): It is accomplished by explicitly

providing property, method, and event information with a related Bean Information
Class. A Bean information class implements the BeanInfo interface. A BeanInfo class
explicitly lists those Bean features that are to be exposed to the application builder
tools. The Introspector recognises BeanInfo classes by their name. The name of a
BeanInfo class is the name of the bean class followed by BeanInfo word e.g., for a
bean named Gizmo the BeanInfo name would be GizmoBeanInfo.

x Properties: Are a Beans appearance and behaviour characteristics that can be

changed at design time.

x Customisation: Beans expose properties so they can be customised during the

design time.

x Events: Enables Beans to communicate and connect to each other.

x Persistence: The capability of permanently stored property changes is known as

Persistence. Beans can save and restore their state i.e., they need to be persistent.
It enables developers to customise Beans in an app builder, and then retrieve
those Beans, with customised features intact, for future use. JavaBeans uses Java
Object Serialisation to support persistence. Serialisation is the process of
writing the current state of an object to a stream. To serialise an object, the class
must implement either java.io.Serialisable or java.io.Externalisable interface.
Beans that implement Serialisable are automatically saved and beans that
implements Externalisable are responsible for saving themselves. The transient
and static variables are not serialised i.e., these type of variables are not stored.

Beans can also be used just like any other Java class, manually (i.e., by hand
programming), due to the basic Bean property, Persistence. Following are the two

x Simply instantiate the Bean class just like any other class.

x If you have a customised Bean (through some graphic tool) saved into a serialised
file (say mybean.ser file), then use the following to create an instance of the
Customised Bean class...
try {
MyBean mybean = (MyBean)
Beans.instantiate(null, "mybean");
} catch (Exception e) {

x Connecting Events: Beans, being primarily GUI components, generate and respond
to events. The bean generating the event is referred to as event source and the bean
listening for (and handling) the event is referred to as the event listener.

x Bean Properties: Bean properties can be categorised as follows...

1) Simple Property are basic, independent, individual prperties like width, height,
and colour.

2) Indexed Property is a property that can take on an array of values.

3) Bound Property is a property that alerts other objects when its value changes.

EJB and XML 4) Constrained Property differs from Bound Property in that it notifies other
objects of an impending change. Constrained properties give the notified objects
the power to veto a property change.

Accessor Methods

1. Simple Property :

If, a bean has a property named foo of type fooType that can be read and written, it
should have the following accessor methods:

public fooType getFoo( ) { return foo; }

public void setFoo(fooType fooValue) {
foo = fooValue; ...

If a property is boolean, getter methods are written using is instead of get eg

isFoo( ).

2. Indexed Property :

public widgetType getWidget(int index)

public widgetType[] getWidget( )
public void setWidget(int index, widgetType widgetValue)
public void setWidget(widgetType[] widgetValues)

3. Bound Property :

Getter and setter methods for bound propery are as described above based on whether
it is simple or indexed. Bound properties require certain objects to be notified when
they change. The change notification is accomplished through the generation of a
PropertyChangeEvent (defined in java.beans). Objects that want to be notified of a
property change to a bound property must register as listeners. Accordingly, the bean
that's implementing the bound property supplies methods of the form:

public void addPropertyChangeListener(ropertyChangeListener l)

public void removePropertyChangeListener(PropertyChangeListener l)

The preceding listener registeration methods do not identify specific bound properties.
To register listeners for the PropertyChangeEvent of a specific property, the following
methods must be provided:

public void addPropertyNameListener(PropertyChangeListener l)

public void emovePropertyNameListener(PropertyChangeListener l)

In the preceding methods, PropertyName is replaced by the name of the bound


Objects that implement the PropertyChangeListener interface must implement the

PropertyChange( ) method. This method is invoked by the bean for all registered
listeners to inform them of a property change.

4. Constrained Property :

The previously discussed methods used with simple and indexed properties also apply

to the constrained properties. In addition, the following event registeration methods Introduction to
Java Beans

public void addVetoableChangeListener(VetoableChangeListener l)

public void removeVetoableChangeListener(VetoableChangeListener l)
public void addPropertyNameListener(VetoableChangeListener l)
public void removePropertyNameListener(VetoableChangeListener l)

Objects that implement the VetoableChangeListener interface must implement the

vetoableChange( ) method. This method is invoked by the bean for all of its registered
listeners to inform them of a property change. Any object that does not approve of a
property change can throw a PropertyVetoException within its vetoableChange( )
method to inform the bean whose constrained property was changed that the change
was not approved.

Inside java.beans package

The classes and packages in the java.beans package can be categorised into three types
(NOTE: following is not the complete list).

1) Design Support
Classes - Beans, PropertyEditorManager, PropertyEditorSupport
Interfaces - Visibility, VisibilityState, PropertyEditor, Customizer

2) Introspection Support.
Classes - Introspector, SimpleBeanInfo, BeanDescriptor, EventSetDescriptor,
FeatureDescriptor, IndexedPropertyDescriptor, MethodDescriptor,
ParameterDescriptor, PropertyDescriptor
Interfaces - BeanInfo

3) Change Event-Handling Support.

Classes - PropertyChangeEvent, VetoableChangeEvent, PropertyChangeSupport,
Interfaces - PropertyChangeListener, VetoableChangeListener


Enterprise JavaBeans are software component models, their purpose is to build/support

enterprise specific problems. EJB - is a reusable server-side software component.
Enterprise JavaBeans facilitates the development of distributed Java applications,
providing an object-oriented transactional environment for building distributed, multi-tier
enterprise components. An EJB is a remote object, which needs the services of an EJB
container in order to execute.

The primary goal of a EJB is WORA (Write Once Run Anywhere). Enterprise JavaBeans
takes a high-level approach to building distributed systems. It frees the application
developer and enables him/her to concentrate on programming only the business logic
while removing the need to write all the plumbing code that's required in any enterprise
application. For example, the enterprise developer no longer needs to write code that
handles transactional behaviour, security, connection pooling, networking or threading.
The architecture delegates this task to the server vendor.


The Enterprise JavaBeans spec defines a server component model and specifies, how to
create server-side, scalable, transactional, multiuser and secure enterprise-level
components. Most important, EJBs can be deployed on top of existing transaction
processing systems including traditional transaction processing monitors, Web, database
and application servers.

A typical EJB architecture consists of:

x EJB clients: EJB client applications utilise the Java Naming and Directory Interface
(JNDI) to look up references to home interfaces and use home and remote EJB
interfaces to utilise all EJB-based functionality.
x EJB home interfaces (and stubs): EJB home interfaces provide operations for
clients to create, remove, and find handles to EJB remote interface objects.
Underlying stubs marshal home interface requests and unmarshal home interface
responses for the client.
x EJB remote interfaces (and stubs): EJB remote interfaces provide business-specific
client interface methods defined for a particular EJB. Underlying stubs marshal
remote interface requests and unmarshal remote interface responses for the client.
x EJB implementations: EJB implementations are the actual EJB application
components implemented by developers to provide any application-specific business
method invocation, creation, removal, finding, activation, passivation, database
storage, and database loading logic.
x Container EJB implementations (skeletons and delegates): The container manages
the distributed communication skeletons used to marshal and unmarshal data sent to
and from the client. Containers may also store EJB implementation instances in a pool
and use delegates to perform any service-management operations related to a
particular EJB before calls are delegated to the EJB implementation instance.
Some of the advantages of pursuing an EJB solution are:

x EJB gives developers architectural independence.

x EJB is WORA for server-side components.
x EJB establishes roles for application development.
x EJB takes care of transaction management.
x EJB provides distributed transaction support.
x EJB helps create portable and scalable solutions.
x EJB integrates seamlessly with CORBA.
x EJB provides for vendor-specific enhancements.


To create an EJB we need to create Home, Remote and Bean classes.
Home Interface

import java.rmi.*;
import javax.ejb.*;
import java.util.*;
public interface HelloObject extends EJBObject {
public String sayHello() throws RemoteException;
Introduction to
Java Beans
Remote Interface

import java.rmi.*;
import javax.ejb.*;
import java.util.*;

public interface HelloHome extends EJBHome {

public HelloObject create() throws RemoteException,

Bean Implementation

import java.rmi.RemoteException;
import javax.ejb.*;

public class HelloBean implements SessionBean {

private SessionContext sessionContext;
public void ejbCreate() {
public void ejbRemove() {
public void ejbActivate() {
public void ejbPassivate() {
public void setSessionContext(SessionContext sessionContext)
this.sessionContext = sessionContext;
public String sayHello() throws java.rmi.RemoteException {
return "Hello World!!!!!";

EJB and XML Deployment Descriptor

<description>HelloWorld deployment descriptor</description>
<description> HelloWorld deployment descriptor

EJB Client

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.transaction.UserTransaction;
import javax.rmi.PortableRemoteObject;

public class HelloClient {

public static void main(String args[]) {
try {
Context initialContext = new InitialContext();
Object objref =
HelloWorldHome home =

HelloWorld myHelloWorld = home.create();
String message = myHelloWorld.sayHello();
} catch (Exception e) {
System.err.println(" Erreur : " + e);

Introduction to
1.7 EJB TYPES Java Beans

EJBs are distinguished along three main functional roles. Within each primary role, the
EJBs are further distinguished according to subroles. By partitioning EJBs into roles, the
programmer can develop an EJB according to a more focused programming model than,
if, for instances such roles were not distinguished earlier. These roles also allow the EJB
container to determine the best management of a particular EJB based on its programming
model type.

There are three main types of beans:

x Session Bean
x Entity Beans
x Message-driven Beans

1.7.1 Session Bean

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. There are two types of session beans:

x Stateless Session Beans: A stateless session EJB is shared between a number of

clients. It does not maintain conversational state. After each method call, the container
may choose to destroy a stateless session bean, or recreate it, clearing itself out, of all
the information pertaining the invocation of the last method. The algorithm for
creating new instance or instance reuse is container specific.

x Stateful Session Beans: A stateful session bean is a bean that is designed to service
business processes that span multiple method requests or transaction. To do this, the
stateful bean retains the state for an individual client. If, the stateful beans state is
changed during method invocation, then, that same state will be available to the same
client upon invocation. Life Cycle of a Stateless Session Bean

The Figure 1 shows the life cycle of a Stateless Session Bean.

Does not exist


Business Methods Ready

Figure 1: Life Cycle of Stateless Session Bean

x Does not exist: In this state, the bean instance simply does not exist.
x Ready state: When EJB Server is first started, several bean instances are created and
placed in the Ready pool. More instances might be created by the container as and
when needed by the EJB container

EJB and XML Life Cycle of a Stateful Session Bean

The Figure 2 shows the life cycle of a Stateful Session Bean.

Does not exist


Business Methods Ready Passive


Figure 2: Life cycle of a stateful session bean

x Does not exist: In this state, the bean instance simply does not exist.
x Ready state: A bean instance in the ready state is tied to a particular client and
engaged in a conversation.
x Passive state: A bean instance in the passive state is passivated to conserve resources. Required Methods in Session Bean

The following are the required methods in a Session Bean:
setSessionContext(SessionContext ctx) :
Associate your bean with a session context. Your bean can make a query to the
context about its current transactional state, and its current security state.
ejbCreate( ) :
Initialise your session bean. You would need to define several ejbCreate () methods and
then, each method can take up different arguments. There should be at least one
ejbCreate() in a session bean.


This method is called for, just before the session bean is passivated and releases any
resource that bean might be holding.


This method is called just for, before the session bean is activated and acquires the
resources that it requires.

This method is called for, by the ejb container just before the session bean is removed
from the memory.

14 The use of a Session Bean Introduction to
Java Beans

In general, one should use a session bean if the following circumstances hold:

x At any given time, only one client has access to the bean instance.
x The state of the bean is not persistent, existing only for a short period and therefore.

x The bean implements a web service.

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

x The beans state represents the interaction between the bean and a specific client.

x The bean needs to hold information about the client across method invocations.

x The bean mediates between the client and the other components of the application,
presenting a simplified view to the client.

x Behind the scenes, the bean manages the work flow of several enterprise beans.

To improve performance, one might choose a stateless session bean if, it has any of these
x The beans state has no data for a specific client.
x 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 a promotional email to
several registered users.

1.7.2 Entity Bean

Entity EJBs represent persistent objects. Their lifetimes is not related to the duration of
interaction with clients. In nearly all cases, entity EJBs are synchronised 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.
An important feature of entity EJBs is that they have identitythat 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.

There are two type of persistence that entity EJB supports. These persistence types are:

x Bean-managed persistence (BMP): The entity beans implementation manages

persistence by coding database access and updating statements in callback methods.

x Container-managed persistence (CMP): The container uses specifications made in

the deployment descriptor to perform database access and update statements

EJB and XML Life Cycle of an Entity Bean
The Figure 3 shows the life cycle of an entity bean.

Does not exist

setEntityContext unsetEntityContext


ejbPostCreate ejbRemove

findByPrimaryKey ejbLoad

Business Methods Ready


Figure 3: Life cycle of an entity bean

An entity bean has the following three states:

x Does not exist: In this state, the bean instance simply does not exist.
x Pooled state: When the EJB server is first started, several bean instances are created
and placed in the pool. A bean instance in the pooled state is not tied to a particular
data, that is, it does not correspond to a record in a database table. Additional bean
instances can be added to the pool as needed, and a maximum number of instances
can be set.
x Ready state: A bean instance in the ready state is tied to a particular data, that is, it
represents an instance of an actual business object. Required Methods in Entity Bean

Entity beans can be bean managed or container managed. Here, are the methods that are
required for entity beans:
This method is called for, if a container wants to increase its pool size of bean instances,
then, it will instantiate a new entity bean instance. This method associates a bean with
context information. Once this method is called for, then, the bean can access the
information about its environment
ejbFind(..): Introduction to
Java Beans
This method is also known as the Finder method. The Finder method locates one or more
existing entity bean data instances in underlying persistent store.

The Home methods are special business methods because they are called from a bean in
the pool before the bean is associated with any specific data. The client calls for, home
methods from home interface or local home interface.
This method is responsible for creating a new database data and for initialising the bean.
There must be one ejbPostCreate() for each ejbCreate(). Each method must accept the
same parameters. The container calls for, ejbPostCreate() right after ejbCreate().
When a client calls for, a business method on a EJB object but no entity bean instance is
bound to EJB object, the container needs to take a bean from the pool and transition into a
ready state. This is called Activation. Upon activation the ejbActivate() method is called
for by the ejb container.

This method is called for, to load the database in the bean instance.


This method is used for, to update the database with new values from the memory. This
method is also called for during ejbPassivate().

This method is called for, by the EJB container when an entity bean is moved from the
ready state to the pool state.
This method is used to destroy the database data. It does not remove the object. The object
is moved to the pool state for reuse.
This method removes the bean from its environment. This is called for, just before
destroying the entity bean. The Use of the Entity Bean

You could probably use an entity bean under the following conditions:

x The bean represents a business entity and not a procedure. For example,
BookInfoBean would be an entity bean, but BookInfoVerifierBean would be a session

x The beans state must be persistent. If the bean instance terminates or if the
Application Server is shut down, the bean's state still exists in persistent storage (a

EJB and XML 1.7.3 Message Driven Bean
A message-driven bean acts as a consumer of asynchronous messages. It cannot be called
for, 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 for, directly by clients, it can
call other EJBs itself. Life Cycle of a Message Driven Bean

The Figure 4 shows the life cycle of a Message Driven Bean:

Does not exist

newInstance ejbRemove

Ready Pool


Figure 4: Life Cycle of a Message Driven Bean

A message driven bean has the following two states:

x Does not exist: In this state, the bean instance simply does not exist. Initially, the
bean exists in the; does not exist state.

x Pooled state: After invoking the ejbCreate() method, the MDB instance is in the
ready pool, waiting to consume incoming messages. Since, MDBs are stateless, all
instances of MDBs in the pool are identical; they're allocated to process a message
and then return to the pool. Method for Message Driven Bean


This method is invoked for each message that is consumed by the bean. The container is
responsible for serialising messages to a single message driven bean.
When this method is invoked, the MDB is first created and then, added to the to pool.


When this method is invoked, the MDB is removed from the to pool.

This method is called for, as a part of the event transition that message driven bean goes
through, when it is being added to the pool. This is called for, just before the ejbCreate().
18 The Use of the Message Driven Bean Introduction to
Java Beans
Session beans allow you to send JMS messages and to receive them synchronously, but
not asynchronously. To avoid tying up server resources, you may prefer not blocking
synchronous receives in a server-side component. To receive messages asynchronously,
use a message-driven bean.
 Check Your Progress 1
1) What is the relationship between Enterprise JavaBeans and JavaBeans?

2) Explain the different types of Enterprise beans briefly.
3) What is the difference between Java Bean and Enterprise Java Bean?

4) Can Entity Beans have no create() methods?
5) What are the call back methods in the Session Bean?
6) What are the call back methods of Entity Beans?
7) Can an EJB send asynchronous notifications to its clients?
8) What is the advantage of using an Entity bean for database operations, over directly
using JDBC API to do database operations? When would I need to use one over the

9) What are the callback methods in Entity beans?