1. 1 | P a g e
E-commerce Systems
Instructor: Dr. Zainab Khallouf
Enterprise JavaBeans (EJB 3.1)
Acknowledgements:
Lecture notes adapted from:
The Java EE 7 Tutorial.
http://docs.oracle.com/javaee/7/tutorial/doc/javaeetutorial7.pdf
Lecture References:
[1]. docs.oracle.com/javaee/7/tutorial/doc/
[2]. http://netbeans.org/kb/docs/javaee/ecommerce
[3]. Enterprise JavaBeans 3.1, sixth edition, by Andrew Lee Rubinger, Bill Burke,
O'Reilly Media.
[4]. Chapter 4 from Distributed Systems Principles and Paradigms, by A. Tanenbaum
and M. Van Steen.
تذكري...السابقة احملاضرة من
القسماملقرر من األول:حتقيمتعدد الكرتونية جتارة تطبيق قاملكوانت ّيضم الطبقاتّاملوضحالشكل يف ة
:التايل
عن اليوم حماضرةSession Beans...
2. 2 | P a g e
يفرتعEnterprise JavaBeans (EJBs):
Enterprise JavaBeans (EJBs) are server-side Java EE components
run in the EJB container and encapsulate the business logic of an
application.
بسيطة بكلمات:EJBsتتضمن جافا صفوف هي( حقولfieldsو )طرقالعمل منطق لتحققيف
التطبيق،اإلضافية اتزالرتمي بعض الصفوف هذه إىل يضافannotationsحاوي يتمكن حىت
مكوانتEJBsأوEJBs containerاملكوانت هذه إدارة منهلا خدمات وتقدمي.
Benefits of Enterprise Beans (Enterprise Beans استخدام ائدو)ف
Enterprise beans can simplify the development of large, distributed
applications.
1. Because the EJBs container provides system-level services
such as security, transaction management, Java Naming and
Directory Interface (JNDI) API lookups, and remote
connectivity to enterprise beans, the bean developer can
concentrate on solving business problems.
2. The enterprise beans are reusable components, and the
application assembler can build new applications from existing
beans.
3. Scalability can be achieved by distributing an application’s
components across multiple machines. The enterprise beans
of an application can run on different machines, and their
location will remain transparent to the clients.
Types of Java Enterprise Beans (EJBs):
1. Session beans.
2. Message-driven beans.
Session Beans
3. 3 | P a g e
What is a Session Bean?
A session bean is a component that encapsulates business
logic and include methods that can be invoked by a client.
Session beans are of three types:
1. stateless,
2. stateful,
3. singleton.
Developing Enterprise Application with Session Beans Using
Netbeans:
Step 1:
Creating new enterprise application in Netbeans.
Step 2:
Name and Location.
4. 4 | P a g e
Step 3:
Server and Settings.
Step 4:
5. 5 | P a g e
The new project.
Step 5:
Adding Libraries to CounterBeanFall16-ejb.
Step 6:
Add session beans.
11. 11 | P a g e
لتوضيحاحمللي الوصول و بعد عن الوصول بني الفرقنرى دعنابني الفرقاملستدعنيو احملليني
املستدعنيالبعيدين( ـلSession Bean.)
Local Clients
A local client has these characteristics.
It must run in the same application as the enterprise bean it
accesses.
It can be a web component or another enterprise bean.
To build an enterprise bean that allows only local access, you may
do one of the following:
Create an enterprise bean implementation class that does not
implement a business interface.
For example:
@Stateless
public class MyBean { ... }
Annotate the business interface of the enterprise bean as a
@Local interface.
For example:
@Local
public interface InterfaceName { ... }
Specify the interface by decorating the bean class with @Local
and specify the interface name.
For example:
@Local(InterfaceName.class)
public class BeanName implements InterfaceName { ... }
Remote Clients
A remote client of an enterprise bean has the following traits:
12. 12 | P a g e
It can run on a different machine and a different JVM from
the enterprise bean it accesses. (It is not required to run on a
different JVM.)
It can be a web component, an application client, or another
enterprise bean.
In this case, the session bean must implement a business
interface.
To create an enterprise bean that allows remote access, you must
either
Decorate the business interface of the enterprise bean with
the @Remote annotation:
@Remote
public interface InterfaceName { ... }
Decorate the bean class with @Remote, specifying the
business interface or interfaces:
@Remote(InterfaceName.class)
public class BeanName implements InterfaceName { ... }
Using Enterprise Beans in Clients
The client of an enterprise bean obtains a reference to an
instance of an enterprise bean through either:
1. Dependency injection
o Dependency injection uses the @EJB annotation from
javax.ejb.EJB
o And specify the enterprise bean's implementation class
or enterprise bean's local business interface name (local
or remote)
13. 13 | P a g e
o Can be used by local clients (i.e. must run in the same
application as the enterprise bean it accesses) or remote
clients that run within a Java EE server-managed
environment. Examples:
Web tier components.
Business tier compononts.
2. JNDI Syntax
عرض قبلكيفيةاستخدامJNDIتوضيب كيفيةعن فكرة أنخذ دعنا(Packaging)تطبيقJAVA
EE
Note About Packaging:
A Java EE application is delivered in a Java Archive (JAR) file, a
Web Archive (WAR) file, or an Enterprise Archive (EAR) file.
o A WAR or EAR file is a standard JAR (.jar) file with a .war
or .ear extension.
An EAR file can contain Java EE modules of the following
types:
o EJB modules, which contain class files for enterprise
beans and, optionally, an EJB deployment descriptor (A
deployment descriptor, an XML document with an .xml
extension, describes the deployment settings of an
application, a module, or a component. ). EJB modules
are packaged as JAR files with a .jar extension.
o Web modules, which contain servlet class files, web files,
supporting class files, GIF and HTML files, and, optionally,
a web application deployment descriptor. Web modules
are packaged as JAR files with a .war (web archive)
extension.
o Application client modules, which contain class files and,
optionally, an application client deployment descriptor.
14. 14 | P a g e
Application client modules are packaged as JAR files
with a .jar extension.
o Resource adapter modules, (A resource adapter is a Java
EE component that implements the Java EE Connector
Architecture for a specific EIS-like enterprise resource
planning). Resource adapter modules are packaged as
JAR files with an .rar (resource adapter archive)
extension.
Packaging Enterprise Beans in WAR Modules:
o Enterprise beans often provide the business logic of a web
application. In these cases, packaging the enterprise bean
within the web application's WAR module simplifies
deployment and application organization.
o Web Module Structure
15. 15 | P a g e
classes: A directory that contains server-side classes:
servlets, enterprise bean class files, utility classes, and
JavaBeans components.
lib: A directory that contains JAR files that contain
enterprise beans, and JAR archives of libraries called
by server-side classes.
Deployment descriptors, such as web.xml (the web
application deployment descriptor) and ejb-jar.xml
(an EJB deployment descriptor).
Example 1:
Example 2:
16. 16 | P a g e
Three JNDI namespaces are used for portable JNDI lookups:
o java:global:
JNDI global addresses are of the following form:
java:global[/application name]/module name
/enterprise bean name[/interface name ]
Application name is required only if the application
is packaged within an Enterprise Archive.
The interface name is required only if the
enterprise bean implements more than one
business interface.
o java:module JNDI namespace used to look up local
enterprise beans within the same module. JNDI
addresses using the java:module namespace are of the
following form:
java:module/enterprise bean name/[interface name]
The interface name is required only if the
enterprise bean implements more than one
business interface.
o java:app JNDI namespace used to look up local
enterprise beans packaged within the same application.
17. 17 | P a g e
JNDI addresses using the java:app namespace are of the
following form:
java:app[/module name]/enterprise bean name
[/interface name]
The module name is optional. The interface name is
required only if the enterprise bean implements
more than one business interface.
o Example:
If an enterprise bean, CounterSession.java, from an
application CounterBean (EAR archive)is packaged
within the module CounterBean-ejb.jar.
The JNDI name using the java:global namespace is:
We can verify this name from the server log.
INFO: EJB5181:Portable JNDI names for EJB CounterSession:
[java:global/CounterBean/CounterBean-
ejb/CounterSession!ejb.CounterSessionRemote,
java:global/CounterBean/CounterBean-ejb/CounterSession]
INFO: EJB5182:Glassfish-specific (Non-portable) JNDI names for EJB
CounterSession: [ejb.CounterSessionRemote,
ejb.CounterSessionRemote#ejb.CounterSessionRemote]
18. 18 | P a g e
INFO: CounterBean a été déployé en 875 ms.
INFO: set()
INFO: count()
Return to page 454 from the JEE 7 Tutorial for further details.
Stateless Session Bean (SLSB)
The SLSB class is annotated with: @Stateless
A stateless session bean does not maintain a conversational
state with the client. When a client invokes the methods of a
stateless bean, the bean's instance variables may contain a
state specific to that client but only for the duration of the
invocation.
Stateless session bean can be easily pooled. Except during
method invocation, all instances of a stateless bean are
equivalent, allowing the EJB container to assign an instance
to any client.
Clients may, however, change the state of instance variables
in pooled stateless beans, and this state is held over to the
next invocation of the pooled stateless bean.
Stateless Session Bean Example Application:
-This application includes a counter SLSB CounterSession, this
bean exposes two methods in a remote interface
CounterSessionRemote: set(int val): set the initial value of the
counter and count() increases by one the value of the counter.
-The client is a JAVA SE application.
19. 19 | P a g e
The CounterSession SLSB and its remote interface
CounterSessionRemote:
The client:
20. 20 | P a g e
The output:
Note 1: in netbeans, every time you change in the code of the bean
you need to “clean and build” then “deploy”
Note 2: About integrating EJB project in the client application.
21. 21 | P a g e
Example 2
Stateful Session Bean (SFSB)
The SFSB class is annotated with: @Stateful
Stateful session beans maintain conversational state, which
means that the instance variables of the bean class can
maintain data specific to a unique client between method
invocations. When the client terminates, its session bean
appears to terminate and is no longer associated with the
client.
Stateful session beans are managed using cache; the size of
the cache specifies the maximum number of session beans
that are held in cache.
22. 22 | P a g e
If the cache overflows (when the number of beans exceeds
max-cache-size), the container then passivate some beans or
writes out the serialized state of the bean into a file.
Stateful Session Bean Example Application:
o This application includes a counter SFSB CounterSession,
this bean exposes three methods in a remote interface
CounterSessionRemote, these methods are: set(int val):
set the initial value of the counter and count() increases
by one the value of the counter, and remove() remove
the SFSB instance.
o The client is a JAVA SE application.
The CounterSession SFSB:
23. 23 | P a g e
package ejb;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remove;
import javax.ejb.Stateful;
@Stateful
public class CounterSession implements CounterSessionRemote {
private int val;
@Override
public int count() {
System.out.println("count()");
val = val + 1;
return val;
}
@Remove
@Override
public void remove() {
System.out.println("remove()");
}
@Override
public void set(int val) {
this.val = val;
System.out.println("set()");
}
@PostConstruct
public void construct() {
System.out.println("construct()");
}
24. 24 | P a g e
@PostActivate
public void activate() {
System.out.println("activate()");
}
@PrePassivate
public void passivate() {
System.out.println("passivate()");
}
@PreDestroy
public void destroy() {
System.out.println("destroy()");
}
}
The callbacks of the Lifecycles of Enterprise Beans:
The callbacks:حياة من خمتلفة احلرم يف معينة مهام بتنفيذ تسمح طرقEnterprise Beans.
o @PostConstruct: Methods annotated with
@PostConstruct are invoked by the container on newly
constructed bean instances (used for stateless , stateful
session bean, and message driven bean)
o @PreDestroy: Methods annotated with @PreDestroy are
invoked after any method annotated @Remove has
completed and before the container removes the
enterprise bean instance. (used for stateless , stateful
session bean, and message driven bean)
o @PostActivate: denote method to be invoked after the
stateful session activation.
o @PrePassivate: denote method to be invoked before the
stateful session passivation.
25. 25 | P a g e
o @Remove: remove the bean after calling the method
annotated by @Remove (Used with stateful session
bean).
The client:
Output
And the server log
26. 26 | P a g e
Singleton Session Beans
A singleton session bean is instantiated once per application and
exists for the lifecycle of the application.
Singleton session bean is shared and concurrently accessed by
clients.
Creating a Singleton Session Bean
The javax.ejb.Singleton annotation is used to specify that the
enterprise bean implementation class is a singleton session bean:
@Singleton
public class SingletonBean { ... }
Initializing Singleton Session Beans
The EJB container is responsible for determining when to
initialize a singleton session bean instance unless the singleton
session bean implementation class is annotated with the
javax.ejb.Startup annotation.
The @javax.ejb.Startup annotation marks that the container
must start the bean instance alongside application startup.
@Startup
27. 27 | P a g e
@Singleton
public class StatusBean {
...
}
Managing Concurrent Access in a Singleton Session Bean
Singleton session beans are designed for concurrent access.
Concurrent access to the singleton’s business methods can be
controlled in two ways:
1. Container-managed concurrency.
2. Bean-managed concurrency.
The javax.ejb.ConcurrencyManagement annotation is used to
specify container-managed or bean-managed concurrency for
the singleton like this:
-avax.ejb.ConcurrencyManagementType.CONTAINER
-javax.ejb.ConcurrencyManagementType.BEAN
By default the container-managed concurrency is used.
Container-Managed Concurrency
1. Annotate a singleton’s business method with:
o @Lock(READ) if the method can be concurrently
accessed with many clients.
o Annotate the business method with @Lock(WRITE) if
the singleton session bean should be locked to other
clients while a client is calling that method.
o If no @Lock annotation is present on the singleton
class, the default lock type, @Lock(WRITE), is applied
to all business methods.
Bean-Managed Concurrency
28. 28 | P a g e
2. Developers who create singletons with bean-managed
concurrency are allowed to use the Java programming
language synchronization primitives.
Singleton Session Bean Example Application
o A simple singleton with one method, getHits, that increments a
counter representing the number of times the method has been
accessed.
o The client is a standalone java client application.
The singleton bean CounterBean
The following version of CounterBean is equivalent to the preceding
version:
package counter.ejb;
29. 29 | P a g e
import javax.ejb.Singleton;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType.CONTAINER;
import javax.ejb.Lock;
import javax.ejb.LockType.WRITE;
@Singleton
@ConcurrencyManagement(CONTAINER)
public class CounterBean {
private int hits = 1;
// Increment and return the number of hits
@Lock(WRITE)
public int getHits() {
return hits++;
}
}
The client:
Output: