Professional Documents
Culture Documents
Unit-1:
J2EE
J2EE Overview:
A long time ago J2EE and, especially, application servers were considered to be too
bloated and "heavyweight." It could be quite tedious and discouraging for developers
to use that technology for developing applications. But since the name of the J2EE
framework changed to Java EE, that assumption is not true anymore. How does Java
EE compare to other enterprise frameworks and what criteria makes a framework
lightweight?
When choosing a technology, one of the most important aspects to consider is the
developers' productivity during the development process. Engineers should spend as
much time as possible implementing use cases and revenue-generating features,
because this is what will move a company towards its goals.
The chosen technology and methods should minimize the time developers spend
waiting for builds, tests, and deployments; configuring applications; implementing
plumbing that is not relevant for business use cases; and configuring the build
environment and the external dependencies. But the majority of available
technologies do not do this.
Birth of J2EE:
Java is an evolving programming language that began with the release of the Java
Development Kit (JDK) During this evolutionary process, the Java development team
included more interfaces and libraries as programmers demanded new APIs These
new features were called extensions APIs that were add-ons to the JDK Sun
Microsystems incorporated these extensions into a new Java development kit called
J2SE Information technology departments of corporations look toward web-centric
applications as a way to economize while offering streamlined services to employees
and customers An increased emphasis was placed on server-side programming and on
development of vendor-independent APIs to access server-side systems Sun
responded by creating the Java Community Process Program that invited corporate
users, vendors, and technologists to develop a standard for enterprise Java APIs The
Java Community Process Program effort resulted in J2EE J2EE is a combination of
several technologies that offer a cohesiveness to bond together server-side systems
and services to produce an industrial-strength scalable environment within which
web-centric applications can thrive A critical ingredient in the development of J2EE is
the collaborative environment fostered by Sun, within which vendors and
technologists come together in the Java Community Process Program to create and
implement Java-based technologies
2-tier Architecture:
The 2-tier architecture is generally the client-server model. The user-system interface
is usually on the client desktop, with the database management services typically
hosted on a more powerful machine, acting as the server to multiple clients. The logic
to implement the business processes is either embedded within the user interfaces or
is divided between both machines. It is commonly the former approach which is used
in this architecture, thereby producing a ‘fat client’ which takes the main load of the
processing.
The limitations of this using this architecture outside the sphere of a LAN with under
100 clients becomes apparent on inspection. Despite the server usually being the
more powerful machine, the bulk of the processing work is made the responsibility of
the smaller client – this results in poor performance if the workload is great.
One other problem, which is particularly the case in the realm of e-commerce, is the
lack of flexibility provided by the 2-tier architecture. It is conceivable (likely, even)
that the means of accessing an application can vary. The client may be a web
browser, a mobile device or a Java Swing application interface; the 2-tier architecture
would need to develop business logic for each type of access in a fat-client scenario
because the business functionality will be sitting on the client machine. This provides
poor maintainability and scalability, as any generic changes which need to be made to
an application would need to be made for each individual access type. However, by
adding an extra layer of abstraction between the client layer and the business
processes, this problem may be overcome.
A move from one server to another might also require code-regeneration, thus
displaying poor portability.
3-tier Architecture:
The problems that arose in the 2-tier architecture appear to stem from the question of
“When there’s more computational logic, should it go on the front end or the back
end?” One solution is to take the view that it does not belong on either the server or
the client. Instead, a middle tier can be introduced in order to take such responsibility
away from both the client and the data-managing server. This results in a 3-tier
architecture which can be summed up as follows:
Middle tiers:
There are a variety of implementations of the middle tier –
1. transaction processing monitors
2. message servers
3. application servers
For the purpose of this paper, the use of application servers shall be concentrated on.
By implementing a 3-tier architecture, clients are shielded from the more complex,
lower-level details of the data source connections, database schema and database
implementation. It allows the decoupling of business process implementation from
user interfaces and database access logic. This approach simplifies application
maintenance – if the backend databases are modified, the data access code or object
may be modified while the client remains unchanged and unaware of any of these
modifications.
It now also becomes possible to have multiple front ends, with all business services
running on the application server, whilst using the same data. This is demonstrated in
figure 1.1.
Database
Web browser
Server
Java
Application Business
Logic
Legacy
Database
Systems
Mobile device
The advantage of adding an extra tier is that it allows for a thin (and therefore, simple)
client. Clients can then be rapidly developed, and easily integrated with existing
applications and systems.
Multi-tier Architecture
Each layer may be dealt with separately, which makes the roles of administration and
maintenance easier. Alterations to one tier may remain transparent to another.
RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans) are two
technologies which Java provides for the purpose of building distributed component
models. These are investigated in depth shortly.
Usability - the ease and speed with which a user can interact with and
understand a system or component.
Interoperability - the ability of two or more systems or components to
exchange information.
Scalability - the ease with which a system or component can be modified to fit
the problem area.
Flexibility - the ease with which modifications to a system or component can
be made – and the ability to make changes to one layer without affecting the
others.
Security – it is possible to set security at each step of the chain to ensure data
is safe.
Multiple access mediums – via WAP, HTTP, etc
Maintainability
Reusability
J2EE Platform
What is J2EE?
J2EE Architecture:
JSP Enterprise
Pages Beans
Web browser
Database
Java
Application
Enterprise
Servlets Database
Beans
Mobile device
The J2EE model has a multi-tiered architecture – the components of the application
are distributed across different machines according to the tier they belong to. Despite
the fact that J2EE applications may have 3 or 4 tiers (as depicted by figure 1.2 ), they
are generally only distributed across three different locations (client machines, a J2EE
server machine, and database machines); hence they are typically viewed as having a
3-tiered architecture. J2EE clients are thin – i.e. actions such as database access or
querying and the execution of complex business logic are carried out by the middle
tier.
APIs JNDI JDBC JMS RMI JavaMail JAXP JAAS JTA Connector
J2EE Platform
Java 2 Standard Edition Platform (J2SE)
The main constituents of J2EE architecture, which shall be expanded on below, are:
J2SE
J2EE components
J2EE containers
J2EE services (provided by API’s)
The J2SE runtime environment underpins the J2EE platform, providing applications
with standard Java facilities and core API’s.
The J2EE environment further extends J2SE services with additional API’s for
developing enterprise applications. Their inclusion in the platform facilitates database
access, transaction management, messaging, security and naming and directory
functionality. The API’s shall be elaborated on shortly.
J2EE components
Enterprise JavaBeans components (or ‘enterprise beans’) capture the business logic of
an application. They are remote objects – the distributable J2EE components.
Servlets are small, plug-in extensions to respond/request-oriented servers; effectively,
they enhance the functionality of a server.
Java ServerPages embed servlet code directly in HTML pages – they are a more
presentation-oriented version of the same technology used by servlets.
These components are written in Java and compiled, as would ordinarily be done with
any other Java program classes. Before it can be executed, a J2EE component must
be assembled into a J2EE application, verified as being well-formed according to the
J2EE specifications, and then deployed into its container. (N.B. Static HTML files
and utility classes - such as JavaBeans components - are not considered to be
components. These are packaged along with the J2EE components at the point of
application assembly.)
J2EE containers
Containers are central to the component-based model propounded by J2EE. They are
standardized runtime environments which implement the relevant API’s required by
the container-held components. They also provide the necessary support for client
access protocols, thus stripping the need for individual components (EJBs, JSPs or
servlets) to be aware of how their communications with clients are handled.
Figure 1.3 presented two of the four types of containers available to J2EE
applications – web containers and EJB containers. The other 2 container-types
specified by J2EE are applet containers and application client containers (in order to
run standard Java application clients).
An application client container runs on the client machine, along with its application
client components. Similarly, an applet container runs on the client machine;
specifically, the applet container is a combination of a web browser and Java plug-in
running together.
However, for the purpose of this paper, the focus will remain on the former two
containers (web and EJB), as these are central to developing e-commerce
applications. Whilst applet and standard application client containers warrant a
mention, it is not necessary here to embellish further on the support they provide to
J2EE applications.
Web containers also run on the J2EE server – their role is to host application web
components. A web container bears responsibility for initializing, invoking, and
managing the life cycle of servlets and JSPs.
J2EE Multi Tiered Architecture
10
DCOT- Unit 1
J2EE services
A brief outline of the API’s which the J2EE platform comprises, should elucidate the
nature of the services provided to application components.
CustomerControllerEJB
An application can use JNDI to look up JDBC connections or to locate the interfaces
which are used to create EJB instances.
JNDI’s other role is to enable access to existing enterprise directory services such as
LDAP (Lightweight Directory Access Protocol), NDS (Novell Directory Services)
and DNS (Domain Name System). This common API is used by applications to
access these naming and directory services rather than have them require a separate
API for each directory service.
An application registers the remote object with the RMI registry (by providing the
object and a String name1) in order to make it available to clients that are on a
separate virtual machine.
1
The name follows the following syntax "rmi://hostname:port/remoteObjectName";
hostname = machine and port = port on which the RMI registry is running. remoteObjectName
is the string name of the remote object. “rmi:”, hostname, & port are optional. Hostname
default = localhost. Port default = 1099. Example – “rmi://localhost:1099/jdbc/B2CDB”
where “jdbc/B2CDB” is the logical name of a DataSource object.
J2EE Multi Tiered Architecture
11
DCOT- Unit 1
A client, wishing to invoke a method on a remote object, queries the RMI registry,
using the lookup method which returns a remote reference to the object (called a
‘stub’). RMI publishes the proxy object implementation to the remote interface. The
client makes calls on the proxy object; the calls are then forwarded by RMI to the
remote JVM and finally on to the remote object. Any return values are sent back
along the same route, via the proxy object, to the client. The service is provided by
the remote object implementation which runs on the server, whilst the stub runs on the
client, acting as a proxy for the remote service.
RMI
Client Server
Stub Interface
Object Object
CustomerControllerEJB
In short, JDBC is a means for passing SQL code from a Java application to a DBMS,
and for processing those results returned. It does this by carrying out the following
stages:
The Connection returned is an open connection which is used for creating JDBC
Statement/PreparedStatement objects which pass SQL statements to the DB.
The above example displays a JNDI-based lookup for accessing a database using a
logical name (jdbc/B2CDB).
JDBC technology implements Java’s "Write Once, Run AnywhereTM" features so as to
run on any DBMS.
JavaMail
This API provides mail services (such as e-commerce mail notifications) – for
sending and receiving email. JavaMail is a platform- and protocol-independent API.
It includes support for commonly used mail protocols such as IMAP, SMTP and
POP3.
J2EE Connector
Connector is an API that connects J2EE platform to existing legacy systems. It
provides the capability to plug in to any EJB server that supports the Connector
architecture.
JavaBeans Components
JavaBeans components are useful, if not exactly central, to J2EE applications. Due to
remote calls tending to be more time-consuming than local calls, it is advantageous to
utilize coarse-grained components. It is possible to reduce the amount of remote
access calls by encapsulating sets of behaviour in JavaBeans objects, which can be
manipulated on the client side, and passing these as method parameters in remote
method calls.
Since the enterprise beans encapsulate the business logic of an application, the client
is relieved of the bulk of any complex or computational processing. The overall result
is a simplified route to writing a thin-client, multi-tiered application.
There are 3 kinds of enterprise bean, each of which is a remote object representing
either a business task or a business entity:
1. Entity bean
2. Session bean
3. Message-driven bean
1) Entity Bean
An entity bean represents a persistent business object – it typically correlates to a
single row of a database table, although it may be stored in an alternative storage
mechanism. An example of an entity bean may be a credit card, a customer or a bank
account. An instance of a customer entity bean, which mapped onto the following
Customer relation example, would encapsulate the data provided by one of the rows
in table 1 – e.g. (03, Bway, Doh, Rangoon, bd@email.net).
An entity bean can be identified by its primary key, which is unique to each object.
This corresponds to the primary key of a table if the storage mechanism is that of a
relational database. In table 1, the primary key for a Customer entity bean would
be its customer ID value. This unique identifier allows a client to locate and create
instances of an entity EJB.
2) Session Bean
A session bean represents a client in the J2EE server – it is created by a client and
executes business tasks in the J2EE server on behalf of the client. Each session bean
may have only one client (whereas an entity bean may have multiple clients), and
once the client terminates, the session bean appears to do likewise. Although they are
not persistent objects – and so their data will be lost in the event of a server or client
crashing – a stateful session bean may maintain state across a conversation with a
client by storing information in its private variables. In this way, it can hold data such
that subsequent method invocations can call on these values within the session-
conversation. It is this ability which allows a Cart session bean to store information
on a shopping client’s selections for the duration of the shopping session. Once the
client-EJB conversation terminates, this data is lost.
A stateless session bean does not maintain a conversational state. All stateless session
beans are identical to one another except during method invocation, when their
instance variables may be assigned specific values. This may be demonstrated by
considering a simple session bean, VerificationEJB, which verifies the validity of a
customer credit card. (For the sake of clarity and simplicity, this example presumes
that the validation can be carried out in one simple step, rather than the more realistic
view which involves contacting banking services, awaiting confirmation or rejection,
all the while holding the data on the customer credit card.) In this scenario, the
session bean does not need to hold any data beyond returning the result of the method
call. However, it will assign values during the actual method invocation (such as
credit card number, expiry date, customer name) in order to check the actual details.
Before doing so and after completing the validation, the session bean holds no
information to distinguish it from any other VerificationEJB session bean. Hence,
it is ‘stateless’.
3) Message-Driven Bean
A message-driven bean shares some similarities with a stateless session bean; it is not
persistent and does not maintain a conversational state with a client. Message-driven
beans are local objects that allow for asynchronous messaging. They listen for
messages from the JMS and are completely decoupled from the clients that send the
message. Unlike the other two enterprise bean types, message-driven beans are not
accessed via interfaces.
EJB Transactions
In order to maintain data integrity, entity beans work within transactions. The fact
that entity beans are shared by multiple clients leaves data liable to lost updates,
uncommitted dependency problems and inconsistent analysis. Hence transaction
management is carried out by the EJB container to handle concurrency issues as well
as partial update problems.
To maintain data integrity, either all of these actions should complete, or they should
all fail. The first line of the code demarcates the beginning of the transaction and sets
the Connection object’s autocommit mode off. This groups all SQL statements that
follow into a single transaction, until there is a call to a commit method (as in this
case) or a rollback method. The commit persists all changes made since the
previous rollback or commit and releases any locks held by the Connection object.
con.setAutoCommit(false);
updateOrders(orderId, customerId, price, status, date);
updateOrderLine(orderList);
updateInventory(orderList);
con.commit();
CheckoutEJB
As has already been stated, entity beans and session beans are remote objects. The
remote client of an enterprise bean may be a web component, a client component or
another enterprise bean; the client may be running in either a separate JVM from the
EJB or in the same one. The internal complexities of the bean are shielded from
clients, who are presented with two interfaces by which they may interact with the
enterprise bean. Both interfaces use RMI protocols. For each method defined in the
interfaces, there must be an implementation which correlates to it in the enterprise
bean class.
The remote interface presents the client with the business methods which may be
invoked on the enterprise bean, and the home interface defines the methods by which
an instance of the bean may be created by the client, along with finder methods (in the
case of entity beans) to locate specific enterprise beans. Figure 1.5 demonstrates
these interactions.
J2EE Server
The enterprise bean class, residing on the server, implements either the SessionBean
interface, or the EntityBean interface (depending on the enterprise bean type). It
contains methods with the same signatures as the remote interface, although it does
not in fact implement the remote interface itself. When a bean is deployed (i.e.
installed), the EJB container generates the remote interface. The implementation of
this interface (EJBObject) acts as a proxy by receiving the method invocations from
the client, then going on to make the appropriate calls on the enterprise bean.
The EJBHome interface, which is also implemented by the EJB container, makes the
enterprise bean’s home interface available to a client by means of JNDI. This has
already been displayed previously in the CustomerControllerEJB excerpts (refer back
to JNDI & RMI API sections). However, further clarification may help to indicate
what parts are played by the various components and containers in client-EJB
interactions. Here follows a similar code extract:
The above example deals with an entity bean, which consists of:
In order to have any interactions with an entity or session bean, a client must locate
the home interface for the bean in question. This is done by calling
InitialContext(), which is the starting point for JNDI name-resolution operations
(i.e. the root of the hierarchy). The handle, customerHome, returned by the JNDI
lookup and narrow methods, provides a reference to the CustomerEJB object (which
is an instance of the entity bean class proper).
However, a client cannot directly instantiate an enterprise bean – only the EJB
container may do so. In order to carry out this feat, the client invokes the create
method provided by the home interface. The create method, which is implemented
in EJBObject, invokes the appropriate ejbCreate method in CustomerEJB and
returns an obect of type Customer.
The direct results on an enterprise bean of calling the ejbCreate method are:
Regarding the create method’s return value, the client can then go on to use this
remote handle to invoke the entity bean’s business methods. To the client’s-eye view,
these business methods appear to run locally, whereas they are, in reality, running
remotely in the session bean.
All enterprise beans must meet certain requirements specified by the EJB API. A
brief overview of the principal elements demanded by this technology will bring
about a wider understanding of the design and implementation of the J2EE application
developed for this project. All explanations given are directed at explaining
enterprise beans with bean-managed persistence. Container-managed persistence is
not addressed, as it is outside the scope of this project, and does not yet provide a
high-level of reliability and support.
Figure 1.5.1 depicts the interactions of a client with an entity bean class via the
remote and home interfaces. In order for these communications to work, there are
certain conventions which must be followed when building the entity bean – clearly
there must be a direct correspondence between those methods available in the
interfaces, and those which the are implemented in the entity bean.
Client
The implementation of the remote and home interfaces is taken care of by the EJB
container, which merely leaves the bean developer to define the interfaces themselves,
and the implementation of the entity bean class.
The EntityBean methods which must be implemented in the bean class are:
setEntityContext, unsetEntityContext, ejbRemove, ejbActivate,
ejbPassivate, ejbLoad, ejbStore. (See EJB Life-Cycles section below).
N.B. ejbLoad refreshes instance variables from the database and ejbStore
writes instance variable values to the database. These two methods are called
by the container before and after (respectively) a business method executes,
thereby synchronizing instance variables of the bean with the database.
Home Interface:
Extends the EJBHome interface:
EJBHome interface extends java.rmi.Remote interfaces. The remote home
interface defines methods which allow a remote client to create, find, and
remove an EJB object.
the primary key or a Collection of primary keys (if ejbFindBy), the return
type here for both these methods is the remote interface type, or a Collection
of remote interface types.
Both method types must throw java.rmi.RemoteException, along with any
other Exceptions thrown by their counterparts.
Remote Interface:
Extends the EJBObject interface:
EJBObject interface extends java.rmi.Remote interfaces. The remote
interface defines business methods which a remote client can call.
Each of the method signatures in the remote interface must match the
signature of a method which is implemented in the enterprise bean class. The
method must throw java.rmi.RemoteException, along with any other
Exceptions thrown by the corresponding EJB class method.
Figure 1.5.2 depicts the interactions of a client with a session bean class via the
remote and home interfaces. There are numerous parallels between session beans and
entity beans. To keep from repetition, the differences between session bean
requirements and those of entity beans (discussed above) shall be addressed here.
Since much of the preceding explanatory content regarding the bean class and its
related interfaces holds equally true for session beans, it should suffice to highlight
only where the architectures diverge.
Client
Home Interface:
As for entity beans, but without any FindBy methods.
Remote Interface:
As for entity beans.
EJB Life-cycles
Entity Bean:
As can be seen in the proceeding diagram, an entity bean passes through a pooled
stage before being activated. To start with, the EJB container creates an instance of
the entity bean and invokes the setEntityContext method, which passes the runtime
entity context to the bean. The instance is then pooled with all the other available
entity bean instances. All pooled instances are identical.
When a client invokes the create method, the EJB container calls ejbCreate and
ejbPostCreate methods. This serves to associate the instance with a particular
identity and moves the instance to the ready stage, where its business methods can be
called. The entity bean may also enter the ready stage if the EJB container calls its
ejbActivate method in order to associate it with an EJB object. When using bean-
managed persistence, ejbCreate and ejbActivate must set the primary key of the
entity bean. If they fail to do so, ejbLoad and ejbStore will not be able to
synchronize its variables with the database.
The EJB container may return the entity bean to the pooled stage by invoking the
ejbPassivate method. Alternatively, a client may call the remove method, resulting
in the EJB container calling the ejbRemove method. This action also results in the
disassociation of the EJB object from the enterprise bean and a return to the pooled
stage.
The final phase of the life-cycle comes about when the EJB container invokes the
unsetEntityContext method and removes the entity bean instance from the pool.
Stateful session beans are initialized after a client calls the create method, which the
EJB container follows up by instantiating the bean, then invoking the
setSessionContext and ejbCreate methods. This places the session bean in the
ready state, where it may execute its business logic.
The session bean may be passivated (which moves it to secondary storage) by the EJB
container calling the ejbPassivate method. If a client invokes a method on the
session bean while it is passivated, the container returns it to the ready stage by
calling the ejbActivate method.
When the client calls the remove method, the container removes the instance from the
ready pool by calling the ejbRemove method. The instance may then be garbage
collected.
The stateless session bean’s life cycle is identical to that of the stateful session bean,
except it is never moved to secondary storage (i.e. it is never passivate) and so only
ever exists in the ready stage or not at all. Stateless session beans are far less
resource-intensive than their stateful relations.
Message-Driven Bean:
Message beans do not have remote and home interfaces defining client access. The
life-cycle is similar to that of the stateless session bean.
Web browser
EIS
(Enterprise
Stand-Alone
Information System)
Client
An enterprise bean module would consist of the enterprise bean class, its home and
remote interfaces, any related files (e.g. a bespoke application-exception class) and a
deployment descriptor. Enterprise bean modules are JAR (Java Archive) files.
A web module would consist of one or more web components (JSP pages or servlets)
along with any static HTML files, image files, helper classes, and the deployment
descriptor for the module. This web module is a WAR (Web Archive) file.
An application client would be packaged into a JAR file in a similar manner.
These modules are assembled in a J2EE application, and the application itself is
packaged in an EAR2 (Enterprise Archive) file, ready to be deployed on the server.
Deployment Descriptor
The deployment descriptor is an XML file which describes the specific configuration
requirements of a module such as security settings, resource references and
transaction management settings. The J2EE server reads the deployment descriptor at
runtime in order to ascertain the configuration requirements of an application.
2
An EAR file is a JAR file with an .ear extension
J2EE Multi Tiered Architecture
27
DCOT- Unit 1
This architecture is demonstrated3 in figure 1.6. The TestEJB entity bean is packaged
with its deployment descriptor in a JAR file (TestJAR) and the web component
TestServlet is packaged in a WAR (TestWAR) along with its deployment descriptor.
These two modules are assembled together in the J2EE application, Test. The EAR
file is not displayed in this view.
Sun also provide the J2EE IDE 2.0 beta release Toolkit which integrates Forte for
Java 2.0, with the J2EE Deploytool. This toolkit was used, at the advice of my project
supervisor, instead of the reference implementation. The results of this choice are
given in full in the Evaluation chapter.
3
The deploytool which presents this view is included in the J2EE reference implementation
J2EE Multi Tiered Architecture
28