Enterprise JAVA Bean
1
Enterprise JAVA Bean
EJB is a development architecture for
Building highly scalable and
Robust enterprise level applications,
To be deployed on J2EE compliant
Application.
EJB3.0 is being a great shift from EJB 2.0
and makes development of EJB based
applications quite easy.
2
What Is an Enterprise Bean?
An enterprise bean is a server-side component that
encapsulates the business logic of an application.
The business logic is the code that fulfills the
purpose of the application.
In an inventory control application, for example,
the enterprise beans might implement the business
logic in methods called checkInventoryLevel and
orderProduct.
By invoking these methods, clients can access the
inventory services provided by the application.
3
EJBs act as an entry point for presentation-tier
technologies like Java Server Faces (JSF) but also for all
external services ( web services).
An EJB container is a runtime environment that provides
services, such as transaction management, concurrency
control, pooling, and security authorization.
Historically, application servers have added other features
such as clustering, load balancing, and failover.
EJB developers can then concentrate on implementing
business logic while the container deals with all the
technical plumbing.
4
Benefits
Simplified development of large scale enterprise level
application.
Application Server/ EJB container provides most of
the system level services like transaction handling,
logging, load balancing, persistence mechanism,
exception handling and so on. Developer has to focus
only on business logic of the application.
EJB container manages life cycle of ejb instances thus
developer needs not to worry about when to
create/delete ejb objects.
5
Types
Type Description
Session Bean Session bean stores data of a particular user
for a single session. It can be stateful or
stateless. It is less resource intensive as
compared to entity beans. Session bean gets
destroyed as soon as user session terminates.
Entity Bean Entity beans represents persistent data
storage. User data can be saved to database
via entity beans and later on can be retrieved
from the database in the entity bean.
Message Message driven beans are used in context of
6
Driven Bean JMS (Java Messaging Service). Message Driven
Session Bean
Stateless
The session bean contains no conversational state
between methods, and any instance can be used for
any client. It is used to handle tasks that can be
concluded with a single method call.
Stateful
The session bean contains conversational state, which
must be retained across methods for a single user. It is
useful for tasks that have to be done in several steps.
Singleton 7
A single session bean is shared between clients and
Message-driven beans (MDBs)
Is used for integrating with external systems by
receiving asynchronous messages using JMS. Even
though MDBs are part of the EJB specification.
MDBs usually delegate the business logic to
session beans
8
Services Given by the Container
State management:
For stateful session beans, the container manages their state
transparently. You can maintain state for a particular client, as if
you were developing a desktop application.
Pooling:
For stateless beans and MDBs, the container creates a pool of
instances that can be shared by multiple clients. Once invoked, an
EJB returns to the pool to be reused instead of being destroyed.
Component life cycle:
The container is responsible for managing the life cycle of each
component.
9
Services Given by the Container
Remote client communication:
Without writing any complex code, an EJB client
(another EJB, a user interface, a batch process,
etc.) can invoke methods remotely via standard
protocols.
Dependency injection:
The container can inject several resources into an
EJB (JMS destinations and factories, datasources,
other EJBs, environment variables, etc.) as well as
any POJO thanks to CDI.
10
Services Given by the Container
Messaging:
The container allows MDBs to listen to destinations and
consume messages without too much JMS plumbing.
Transaction management:
With declarative transaction management, an EJB can use
annotations to inform the container about the transaction
policy it should use. The container takes care of the commit
or the rollback.
Security:
Class or method-level access control can be specified on
EJBs to enforce user and role authorization.
11
Services Given by the Container
Concurrency support:
Except for singletons, where some concurrency
declaration is needed, all the other types of EJB are
thread-safe by nature. You can develop high-
performance applications without worrying about
thread issues.
Asynchronous method invocation:
Since EJB 3.1, it’s now possible to have asynchronous
calls without involving messaging.
12
EJBs a set of service cannot create or
manage
threads,
access files using java.io,
create a ServerSocket,
load a native library, or
use the AWT (Abstract Window Toolkit)or
Swing APIs to interact with the user.
13
EJB Lite
The specification defines a minimal subset
of the full EJB API known as EJB Lite.
It includes a small, powerful selection of
EJB features suitable for writing portable
transactional and secure business logic.
Any EJB Lite application can be deployed
on any Java EE product that implementsEJB
3.2.
14
Comparison Between EJB Lite and Full
EJB
Feature EJB Full EJB
Lite 3.2
Session beans (stateless, stateful, singleton) Yes Yes
No-interface view Yes Yes
Local interface Yes Yes
Interceptors Yes Yes
Transaction support Yes Yes
Security Yes Yes
Embeddable API Yes Yes
Asynchronous calls No Yes
MDBs No Yes
15
Remote interface No Yes
JAX-WS web services No Yes
Anatomy of an EJB
A bean class:
The bean class contains the business method
implementation and can implement zero or
several business interfaces. The session bean
must be annotated with @Stateless, @Stateful,
or @Singleton depending on its type.
Business interfaces:
These interfaces contain the declaration of
business methods that are visible to the client 16
and implemented by the bean class. A session
Bean class has several types of business
interfaces
17
Remote, Local, and No-Interface Views
18
EJB - Environment Setup
EJB is a framework for Java, so the very
first requirement is to have JDK installed in
your machine.
19
Create Project
20
21
22
EJB - Stateless Bean
A stateless session bean is a type of
enterprise bean which is normally used to
do independent operations.
A stateless session bean as per its name
does not have any associated client state,
but it may preserve its instance state.
EJBContainer normally creates a pool of
few stateless bean's objects and use these 23
objects to process client's request. Because
Steps required to create a stateless EJB
Create a remote/local interface exposing the business methods.
This interface will be used by the EJB client application.
Use @Local annotation if EJB client is in same environment where EJB
session bean is to be deployed.
Use @Remote annotation if EJB client is in different environment
where EJB session bean is to be deployed.
Create a stateless session bean implementing the above interface.
Use @Stateless annotation to signify it a stateless bean. EJB Container
automatically creates the relevant configurations or interfaces
required by reading this annotation during deployment.
24
Remote Interface
import javax.ejb.Remote;
@Remote
public interface
LibrarySessionBeanRemote {
//add business method declarations
}
25
Stateless EJB
@Stateless
public class LibrarySessionBean implements
LibrarySessionBeanRemote {
//implement business method
}
26
Enterprise JavaBean Architecture
The Enterprise JavaBeans architecture defines a
standard model for Java application servers to
support “Write Once, Run Anywhere” (WORA)
portability
EJB technology takes the WORA concept to a new
level.
EJB completely portable across any vendor’s EJB
compliant application server. The EJB environment
automatically maps the component to the
underlying vendor-specific infrastructure services.
27
Enterprise JavaBeans
The EJB architecture specifies the responsibilities
and interactions among EJB entities
EJB Servers
Enterprise Enterprise
EJB Containers Bean Bean
Enterprise Beans Clients EJB Container
Clients
EJB Server
EJB Clients
28
EJB Server
Providesa Runtime Environment
The EJB Server provides system services
and manages resources
Process and thread management
System resources management
Database connection pooling and caching
Management API
29
EJB Container
Provides a Run-time Environment for an Enterprise Bean
Hosts the Enterprise JavaBeans
Provides services to Enterprise JavaBeans
Naming
Life cycle management
Persistence (state management)
Transaction Management
Security
Likely provided by server vendor
30
Enterprise JavaBeans
A specialized Java class where the real
business logic lives Enterprise
Bean
Enterprise
Bean
May be developer-written or tool- EJB Container
generated EJB Server
Distributed over a network
Transactional
Secure
31
Server vendors provide tools that
EJB Clients
Clientaccess is controlled by the container
in which the enterprise Bean is deployed
Clientslocates an Enterprise JavaBean
through Java Naming and Directory
Interface (JNDI)
RMI
is the standard method for accessing a
bean over a network
32
What’s Unique About EJB
Declarative Programming Model
Mandates a container model where common services are
declared, not programmed
Atdevelopment and/or deployment time, attributes
defining the bean’s transaction and security
characteristics are specified
At deployment time, the container introspects the
Enterprise JavaBean attributes for the runtime services
it requires and wraps the bean with the required
functionality 33
At runtime, the container intercepts all calls to the
Entity Bean
Represents Data
Implements javax.ejb.EntityBean interface
Maps a data source to a Java class
table, view, join or stored procedure in a
relational database
a set of related records in a database
legacy data
Each instance of an entity bean is one row of data
34
Each instance of an entity bean is uniquely
Comparing Session and Entity Beans
Session Beans Entity Beans
• Mandatory for EJB • Optional for EJB 1.0
1.0 • Represents underlying
• Represents a specific data object or context
(clients share instance)
client • Long-lived
(1 instance per • Persistent
client) • Can be a class that
• Short-lived maps to persistent data
• Transient (e.g., database) 35
• Always transactional
EJB Persistence
Provides Entity Beans the ability to
store and retrieve their state
Can be implemented by a bean
Bean Managed Persistence
Can be implemented by a container
Container Managed Persistence
36
Bean Managed Persistence
The entity bean is responsible for its persistent behavior
EJB developer must implement database access
ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()
Not automated, developer manually creates mapping
through JDBC calls
Not as reusable
Hard-code database access within class
Advanced features like connection pooling and caching are
difficult to support because of reliance on hand written
code
37
Container Managed Persistence
The EJB container is responsible for persistence
The container provides tools that generate code in the
EJB class that maps methods in the bean to a result set
Can map to a table, view, join or stored procedure in a
database
Server provides automated mapping to convert
relational data to bean instances
Advanced features like connection pooling and caching are
easily supported
High reuse
38
1. Servlet-->
<!-- addNumbers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Two Numbers</title>
</head>
<body>
<form action="AddServlet" method="POST">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required>
<br><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2" required>
<br><br>
<button type="submit">Add</button>
</form>
39
</body>
</html>
Step 2: Create the servlet AddServlet to process the form data.
// AddServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AddServlet") //registers this servlet at the URL path /AddServlet.
public class AddServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
response.setContentType("text/html");
response.getWriter().println("Sum of " + num1 + " and " + num2 + " is " + sum); //writes the result as HTML back to the client
40
}
}
Option 2: Using JavaBeans : step 1 Html
file
<!-- addNumbersBean.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Two Numbers Using JavaBean</title>
</head>
<body>
<form action="AddBeanServlet" method="POST">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required>
<br><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2" required>
<br><br>
<button type="submit">Add</button>
</form>
</body>
</html>
41
Summary of method 1
The servlet approach directly handles form submission, parses data, performs
addition, and sends the result back in the response. However, it does not
separate logic into reusable components.
42
Using JavaBeans Step 2: Create CalculatorBean JavaBean for business logic.
// CalculatorBean.java
import java.io.Serializable;
public class CalculatorBean implements Serializable {
private int num1;
private int num2;
// Getters and setters
public int getNum1() {
return num1; }
public void setNum1(int num1) {
this.num1 = num1; }
public int getNum2() {
return num2; }
public void setNum2(int num2) {
this.num2 = num2; }
public int getSum() {
return num1 + num2; 43
}}
Step 3: Create a servlet that uses CalculatorBean to add two numbers.
This servlet handles the HTTP POST request, interacts with the CalculatorBean to get the sum, and sends the response back to the user.
// AddBeanServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AddBeanServlet")
public class AddBeanServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
CalculatorBean calculatorBean = new CalculatorBean();
calculatorBean.setNum1(num1);
calculatorBean.setNum2(num2);
int sum = calculatorBean.getSum();
response.setContentType("text/html");
response.getWriter().println("Sum of " + num1 + " and " + num2 + " is " + sum);
44
}}
Summary of method 2
1.@WebServlet("/AddBeanServlet"): Maps this servlet to the /AddBeanServlet URL.
2.doPost Method: Handles POST requests from the form in addNumbersBean.html.
3.Get Numbers: Retrieves num1 and num2 from the form input using request.getParameter.
4.Create CalculatorBean: Initializes CalculatorBean and sets num1 and num2 using the setters.
5.Calculate Sum: Calls getSum() on calculatorBean to get the addition result.
6.Output Response: Sets response content type and prints the sum to the browser.
45
Option 3: Using EJB
To implement the third option using Enterprise JavaBeans (EJB), we will create an EJB
component that performs the addition of two numbers. In this example, we’ll use a
stateless session bean with a remote interface, making the EJB accessible remotely
if needed. The implementation will include the following steps:
1.Remote Interface: Defines the method for addition that will be accessible to clients.
2.EJB Implementation: Implements the addition logic in a stateless session bean.
3.Servlet: Acts as a client to call the EJB and display the result.
4.HTML Form: A simple HTML file to get the user input for the two numbers.
Step 1: Create the Remote Interface
The remote interface defines the method add(int num1, int num2) that the client will
use to access the EJB.
46
Option 3: Using EJB :step 1
@Remote
public interface CalculatorBeanRemote {
int add(int num1, int num2);
}
•This is the remote interface that the EJB will implement. The @Remote annotation allows remote clients to access
this EJB across the network.
•add method specifies the addition logic that the EJB will provide.
•The @Remote interface in EJB specifies that the bean's methods can be called by clients located in a different
Java Virtual Machine (JVM). This means that the interface is used to access the EJB remotely, which is common in
distributed applications. The CalculatorBeanRemote interface serves as a contract that defines which methods are
accessible to clients, ensuring that clients interact with the EJB through a standard set of methods.
47
Step 2: Implement the Stateless Session Bean
The CalculatorBean class implements the CalculatorBeanRemote interface and provides the business
logic for the addition operation. We use the @Stateless annotation to indicate that this is a stateless
session bean.
// CalculatorBean.java
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean implements CalculatorBeanRemote {
@Override
public int add(int num1, int num2) {
return num1 + num2;
}
}
48
Step 3: Create the Servlet to Access the EJBThe servlet (AddServlet) acts as a
client of the EJB. It receives user input, interacts with the EJB to calculate
the sum, and displays the result.
49
// AddServlet.java
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
@EJB //This annotation injects an instance of CalculatorBeanRemote into the servlet, allowing it to access the EJB.
private CalculatorBeanRemote calculatorBean;
@Override
//doPost: Handles the form submission via HTTP POST. It retrieves input values, calls the EJB’s add method to get the sum, and sends the result back to the client.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve user inputs from the form
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
// Call the EJB method to perform addition
int sum = calculatorBean.add(num1, num2);
// Display the result to the user
response.setContentType("text/html"); 50
response.getWriter().println("Sum of " + num1 + " and " + num2 + " is " + sum); }}
Step 4: Create the HTML Form for User InputThe HTML form (addNumbersEJB.html) gathers the two numbers from the
user and sends them to the servlet.
<!-- addNumbersEJB.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Two Numbers Using EJB</title>
</head>
<body>
<form action="AddServlet" method="POST">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required>
<br><br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2" required>
<br><br>
<button type="submit">Add</button>
</form>
</body> 51
</html>
Summary of Workflow
HTML Form (addNumbersEJB.html): Collects user input (two numbers) and submits to AddServlet.
Servlet (AddServlet): Processes form data, invokes the EJB, and displays the result.
EJB Remote Interface (CalculatorBeanRemote): Defines the add method for the EJB.
EJB Implementation (CalculatorBean): Implements the addition logic.
How to Run the ApplicationDeploy:
Deploy the EJB (CalculatorBean) and the servlet (AddServlet) in an application server that supports
EJB (like GlassFish or WildFly).
Access the Form: Open addNumbersEJB.html in a web browser.
Submit Form: Enter two numbers and submit to see the result, which is displayed after calculation
by the EJB.
This setup demonstrates using EJB with a remote interface and shows how the servlet acts as a
client to the EJB, handling the presentation layer while the EJB encapsulates the business logic for
addition.
52
Remote, Local, and No-Interface
EJB supports three types of access interfaces:
Beans
Explained
Remote, Local, and No-Interface beans.
Each has a specific use case, depending on the client’s location and the application's architecture.
A. Remote Interface (@Remote)
•Usage: When the EJB needs to be accessed from clients located in different JVMs or from different
application servers.
•Client Location: Remote clients, such as those running on a separate server, can interact with the bean.
•Communication Overhead: Higher due to remote communication, usually relying on protocols like RMI
(Remote Method Invocation).
Local Interface (@Local)
•Usage: When the EJB is only accessed within the same application or JVM, such as from other EJBs or servlets in the
same application server.
•Client Location: Clients within the same JVM, so the local interface is faster and more efficient than the remote
interface.
53
C. No-Interface Bean
•Usage: When no explicit interface is needed, allowing clients within the same application to
access the bean directly.
•Annotation: The bean is simply annotated with @Stateless (or @Stateful), without
implementing a separate interface.
•Client Location: This is also local-only, as no-interface beans can’t be accessed remotely.
•Example:
@Stateless
public class CalculatorBean {
public int add(int num1, int num2) {
return num1 + num2;
}
}
Here, the CalculatorBean itself serves as the interface. Local components, such as servlets or
other EJBs, would inject or look up CalculatorBean directly without an interface.
54