EJB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

What is EJB

EJB is an acronym for enterprise java bean. It is a specification provided by Sun


Microsystems to develop secured, robust and scalable distributed applications.
To get information about distributed applications.
To run EJB application, you need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc. It performs:
a. life cycle management,
b. security,
c. transaction management, and
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from
Java Bean, RMI and Web Services.

When use Enterprise Java Bean?


1. Application needs Remote Access. In other words, it is distributed.
2. Application needs to be scalable. EJB applications supports load balancing,
clustering and fail-over.
3. Application needs encapsulated business logic. EJB application is separated from
presentation and persistent layer.

Types of Enterprise Java Bean


There are 3 types of enterprise bean in java.
Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice
client.
Message Driven Bean
Like Session Bean, it contains the business logic but it is invoked by passing message.
Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API).
Difference between RMI and EJB
Both RMI and EJB, provides services to access an object running in another JVM (known as
remote object) from another JVM. The differences between RMI and EJB are given below:

RMI EJB

In RMI, middleware services such as security,


In EJB, middleware services are provided by
transaction management, object pooling etc.
EJB Container automatically.
need to be done by the java programmer.

RMI is not a server-side component. It is not EJB is a server-side component, it is required to


required to be deployed on the server. be deployed on the server.

RMI is built on the top of socket programming. EJB technology is built on the top of RMI.

EJB and Webservice


In EJB, bean component and bean client both must be written in java language.
If bean client need to be written in other language such as .net, php etc, we need to go
with webservices (SOAP or REST). So EJB with web service will be better option.

Disadvantages of EJB
1. Requires application server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop ejb applications.

Session Bean

1. Session bean encapsulates business logic only, it can be invoked by local, remote and
webservice client.
2. It can be used for calculations, database access etc.
3. The life cycle of session bean is maintained by the application server (EJB Container).

Types of Session Bean

There are 3 types of session bean.


1) Stateless Session Bean: It doesn't maintain state of a client between multiple
method calls.
2) Stateful Session Bean: It maintains state of a client across multiple requests.
3) Singleton Session Bean: One instance per application, it is shared between clients
and supports concurrent access.
Stateless Session Bean

Stateless Session bean is a business object that represents business logic only. It doesn't have
state (data).

In other words, conversational state between multiple method calls is not maintained by the
container in case of stateless session bean.

The stateless bean objects are pooled by the EJB container to service the request on demand.

It can be accessed by one client at a time. In case of concurrent access, EJB container routes
each request to different instance.

Annotations used in Stateless Session Bean

There are 3 important annotations used in stateless session bean:

1. @Stateless
2. @PostConstruct
3. @PreDestroy

Life cycle of Stateless Session Bean

There is only two states of stateless session bean: does not exist and ready. It is explained by
the figure given below.

EJB Container creates and maintains a pool of session bean first. It injects the dependency if
then calls the @PostConstruct method if any. Now actual business logic method is invoked by
the client. Then, container calls @PreDestory method if any. Now bean is ready for garbage
collection.

Example of Stateless Session Bean


To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
1) Create stateless bean component
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
6. int add(int a,int b);
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
5. public class AdderImpl implements AdderImplRemote {
6. public int add(int a,int b){
7. return a+b;
8. }
9. }

2) Create stateless bean client


The stateless bean client may be local, remote or webservice client. Here, we are going to
create remote client. It is console based application. Here, we are not using dependency
injection. The dependency injection can be used with web based client only.
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
5. public class Test {
6. public static void main(String[] args)throws Exception {
7. Context context=new InitialContext();
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
Output
Output: 64
Stateful Session Bean
Stateful Session bean is a business object that represents business logic like stateless session
bean. But, it maintains state (data).
In other words, conversational state between multiple method calls is maintained by the
container in stateful session bean.

Annotations used in Stateful Session Bean


There are 5 important annotations used in stateful session bean:
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate

Example of Stateful Session Bean


To develop stateful session bean application, we are going to use Eclipse IDE and glassfish
3 server.
Backward Skip 10sPlay VideoForward Skip 10s
As described in the previous example, you need to create bean component and bean client for
creating session bean application.
1) Create stateful bean component
Let's create a remote interface and a bean class for developing stateful bean component.
File: BankRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3. @Remote
4. public interface BankRemote {
5. boolean withdraw(int amount);
6. void deposit(int amount);
7. int getBalance();
8. }
File: Bank.java
1. package com.javatpoint;
2. import javax.ejb.Stateful;
3. @Stateful(mappedName = "stateful123")
4. public class Bank implements BankRemote {
5. private int amount=0;
6. public boolean withdraw(int amount){
7. if(amount<=this.amount){
8. this.amount-=amount;
9. return true;
10. }else{
11. return false;
12. }
13. }
14. public void deposit(int amount){
15. this.amount+=amount;
16. }
17. public int getBalance(){
18. return amount;
19. }
20. }

2) Create stateful bean client


The stateful bean client may be local, remote or webservice client. Here, we are going to
create web based client and not using dependency injection.
File: index.jsp
1. <a href="OpenAccount">Open Account</a>
File: operation.jsp
1. <form action="operationprocess.jsp">
2. Enter Amount:<input type="text" name="amount"/><br>
3.
4. Choose Operation:
5. Deposit<input type="radio" name="operation" value="deposit"/>
6. Withdraw<input type="radio" name="operation" value="withdraw"/>
7. Check balance<input type="radio" name="operation" value="checkbalance"/>
8. <br>
9. <input type="submit" value="submit">
10. </form>
File: operationprocess.jsp
1. <%@ page import="com.javatpoint.*" %>
2. <%
3. BankRemote remote=(BankRemote)session.getAttribute("remote");
4. String operation=request.getParameter("operation");
5. String amount=request.getParameter("amount");
6.
7. if(operation!=null){
8.
9. if(operation.equals("deposit")){
10. remote.deposit(Integer.parseInt(amount));
11. out.print("Amount successfully deposited!");
12. }else
13. if(operation.equals("withdraw")){
14. boolean status=remote.withdraw(Integer.parseInt(amount));
15. if(status){
16. out.print("Amount successfully withdrawn!");
17. }else{
18. out.println("Enter less amount");
19. }
20. }else{
21. out.println("Current Amount: "+remote.getBalance());
22. }
23. }
24. %>
25. <hr/>
26. <jsp:include page="operation.jsp"></jsp:include>
File: OpenAccount.java
1. package com.javatpoint;
2. import java.io.IOException;
3. import javax.ejb.EJB;
4. import javax.naming.InitialContext;
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. @WebServlet("/OpenAccount")
11. public class OpenAccount extends HttpServlet {
12. //@EJB(mappedName="stateful123")
13. //BankRemote b;
14. protected void doGet(HttpServletRequest request, HttpServletResponse response)
15. throws ServletException, IOException {
16. try{
17. InitialContext context=new InitialContext();
18. BankRemote b=(BankRemote)context.lookup("stateful123");
19.
20. request.getSession().setAttribute("remote",b);
21. request.getRequestDispatcher("/operation.jsp").forward(request, response);
22.
23. }catch(Exception e){System.out.println(e);}
24. }
25. }

You might also like