0% found this document useful (0 votes)
3 views

EJB Tutorial

java Beans

Uploaded by

sandeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

EJB Tutorial

java Beans

Uploaded by

sandeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

EJB Tutorial

EJB (Enterprise Java Bean) is used to develop scalable, robust and secured enterprise applications in
java.

Unlike RMI, middleware services such as security, transaction management etc. are provided by EJB
Container to all EJB applications.

The current version of EJB is EJB 3.2. The development of EJB 3 is faster than EJB 2 because of
simplicity and annotations such as @EJB, @Stateless, @Stateful, @ModelDriven, @PreDestroy,
@PostConstruct etc.

Topics of EJB Specification

The topics of EJB specifications covered by javatpoint is given below.

PlayNext

Mute

Current Time 0:00

Duration 18:10

Loaded: 0.37%

Fullscreen

Backward Skip 10sPlay VideoForward Skip 10s

What is EJB

What is enterprise java beans(EJB) and what are the advantages of EJB?

Session Bean

The session bean represents the business logic. It may be stateless, stateful or singleton.

Stateless Session Bean

What is stateless session bean, its lifecycle and example.

Stateful Session Bean

What is stateful session bean, its lifecycle and example.

JMS Tutorial

How to create robust and asynchronous message for distributed applications. What are messaging
domains?

What is Java Messsage Service and what are the advantages of JMS.
What is JMS Queue? It is used for peer to peer messaging where a single message is delivered to only
one receiver.

What is JMS Topic? It is also known as Publisher and Subscriber model where a single message is
delivered to all the subscribers.

Message Driven Bean

A MDB is a JMS client that is invoked by passing message. It is deployed on the application server.

Entity Bean

In EJB 3.2, it is deprecated. Now it is replaced with JPA.

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, visit RMI Tutorial first.

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, transaction


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

RMI is not a server-side component. It is not required to be EJB is a server-side component, it is required to be
deployed on the server. 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 application.

4. Session Bean
5. Session bean encapsulates business logic only, it can be invoked by
local, remote and webservice client.
6. It can be used for calculations, database access etc.
7. The life cycle of session bean is maintained by the application server
(EJB Container).
8. Types of Session Bean
9. There are 3 types of session bean.
10. 1) Stateless Session Bean: It doesn't maintain state of a client
between multiple method calls.
11. 2) Stateful Session Bean: It maintains state of a client across
multiple requests.
12. 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.

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. }

JMS Tutorial

JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication.

JMS is also known as a messaging service.


Understanding Messaging

Messaging is a technique to communicate applications or software components.

JMS is mainly used to send and receive message from one application to another.

Requirement of JMS

Generally, user sends message to application. But, if we want to send message from one application
to another, we need to use JMS API.

Consider a scenario, one application A is running in INDIA and another application B is running in
USA. To send message from A application to B, we need to use JMS.

Advantage of JMS

1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.

2) Reliable: It provides assurance that message is delivered.

Messaging Domains

There are two types of messaging domains in JMS.

1. Point-to-Point Messaging Domain

2. Publisher/Subscriber Messaging Domain

1) Point-to-Point (PTP) Messaging Domain

In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM).

The Queue is responsible to hold the message until receiver is ready.

In PTP model, there is no timing dependency between sender and receiver.

2) Publisher/Subscriber (Pub/Sub) Messaging Domain

In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Here, Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.
In PTP model, there is timing dependency between publisher and subscriber.

JMS Programming Model

JMS Queue Example

To develop JMS queue example, you need to install any application server. Here, we are
using glassfish3 server where we are creating two JNDI.

1. Create connection factory named myQueueConnectionFactory

2. Create destination resource named myQueue

After creating JNDI, create server and receiver application. You need to run server and receiver in
different console. Here, we are using eclipse IDE, it is opened in different console by default.

1) Create connection factory and destination resource

Open server admin console by the URL http://localhost:4848


Login with the username and password.

Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the
Resource Type as QueueConnectionFactory then click on ok button.

Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical
destination name then click on ok button.
2) Create sender and receiver application

Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will be
invoked when user sends message.

File: MySender.java

1. import java.io.BufferedReader;

2. import java.io.InputStreamReader;

3. import javax.naming.*;

4. import javax.jms.*;

5.

6. public class MySender {

7. public static void main(String[] args) {

8. try

9. { //Create and start connection

10. InitialContext ctx=new InitialContext();

11. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti


onFactory");

12. QueueConnection con=f.createQueueConnection();


13. con.start();

14. //2) create queue session

15. QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

16. //3) get the Queue object

17. Queue t=(Queue)ctx.lookup("myQueue");

18. //4)create QueueSender object

19. QueueSender sender=ses.createSender(t);

20. //5) create TextMessage object

21. TextMessage msg=ses.createTextMessage();

22.

23. //6) write message

24. BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

25. while(true)

26. {

27. System.out.println("Enter Msg, end to terminate:");

28. String s=b.readLine();

29. if (s.equals("end"))

30. break;

31. msg.setText(s);

32. //7) send message

33. sender.send(msg);

34. System.out.println("Message successfully sent.");

35. }

36. //8) connection close

37. con.close();

38. }catch(Exception e){System.out.println(e);}

39. }

40. }

File: MyReceiver.java

1. import javax.jms.*;

2. import javax.naming.InitialContext;
3.

4. public class MyReceiver {

5. public static void main(String[] args) {

6. try{

7. //1) Create and start connection

8. InitialContext ctx=new InitialContext();

9. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti
onFactory");

10. QueueConnection con=f.createQueueConnection();

11. con.start();

12. //2) create Queue session

13. QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

14. //3) get the Queue object

15. Queue t=(Queue)ctx.lookup("myQueue");

16. //4)create QueueReceiver

17. QueueReceiver receiver=ses.createReceiver(t);

18.

19. //5) create listener object

20. MyListener listener=new MyListener();

21.

22. //6) register the listener object with receiver

23. receiver.setMessageListener(listener);

24.

25. System.out.println("Receiver1 is ready, waiting for messages...");

26. System.out.println("press Ctrl+c to shutdown...");

27. while(true){

28. Thread.sleep(1000);

29. }

30. }catch(Exception e){System.out.println(e);}

31. }

32.
33. }

File: MyListener.java

1. import javax.jms.*;

2. public class MyListener implements MessageListener {

3.

4. public void onMessage(Message m) {

5. try{

6. TextMessage msg=(TextMessage)m;

7.

8. System.out.println("following message is received:"+msg.getText());

9. }catch(JMSException e){System.out.println(e);}

10. }

11. }

Run the Receiver class first then Sender class.

JMS Topic Example

It is same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and Receiver
to Subscriber.

You need to create 2 JNDI named myTopicConnectionFactory and myTopic.

File: MySender.java

1. import java.io.BufferedReader;

2. import java.io.InputStreamReader;

3. import javax.naming.*;

4. import javax.jms.*;

5.

6. public class MySender {

7. public static void main(String[] args) {

8. try

9. { //Create and start connection

10. InitialContext ctx=new InitialContext();

11. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa


ctory");
12. TopicConnection con=f.createTopicConnection();

13. con.start();

14. //2) create queue session

15. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

16. //3) get the Topic object

17. Topic t=(Topic)ctx.lookup("myTopic");

18. //4)create TopicPublisher object

19. TopicPublisher publisher=ses.createPublisher(t);

20. //5) create TextMessage object

21. TextMessage msg=ses.createTextMessage();

22.

23. //6) write message

24. BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

25. while(true)

26. {

27. System.out.println("Enter Msg, end to terminate:");

28. String s=b.readLine();

29. if (s.equals("end"))

30. break;

31. msg.setText(s);

32. //7) send message

33. publisher.publish(msg);

34. System.out.println("Message successfully sent.");

35. }

36. //8) connection close

37. con.close();

38. }catch(Exception e){System.out.println(e);}

39. }

40. }

File: MyReceiver.java

1. import javax.jms.*;
2. import javax.naming.InitialContext;

3.

4. public class MyReceiver {

5. public static void main(String[] args) {

6. try {

7. //1) Create and start connection

8. InitialContext ctx=new InitialContext();

9. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa
ctory");

10. TopicConnection con=f.createTopicConnection();

11. con.start();

12. //2) create topic session

13. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

14. //3) get the Topic object

15. Topic t=(Topic)ctx.lookup("myTopic");

16. //4)create TopicSubscriber

17. TopicSubscriber receiver=ses.createSubscriber(t);

18.

19. //5) create listener object

20. MyListener listener=new MyListener();

21.

22. //6) register the listener object with subscriber

23. receiver.setMessageListener(listener);

24.

25. System.out.println("Subscriber1 is ready, waiting for messages...");

26. System.out.println("press Ctrl+c to shutdown...");

27. while(true){

28. Thread.sleep(1000);

29. }

30. }catch(Exception e){System.out.println(e);}

31. }
32.

33. }

File: MyListener.java

1. import javax.jms.*;

2. public class MyListener implements MessageListener {

3.

4. public void onMessage(Message m) {

5. try{

6. TextMessage msg=(TextMessage)m;

7.

8. System.out.println("following message is received:"+msg.getText());

9. }catch(JMSException e){System.out.println(e);}

10. }

11. }

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.

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. }

JMS Tutorial

JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication.

JMS is also known as a messaging service.

Understanding Messaging

Messaging is a technique to communicate applications or software components.

JMS is mainly used to send and receive message from one application to another.

Requirement of JMS

Generally, user sends message to application. But, if we want to send message from one application
to another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another application B is running in
USA. To send message from A application to B, we need to use JMS.

Advantage of JMS

1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.

2) Reliable: It provides assurance that message is delivered.

Messaging Domains

There are two types of messaging domains in JMS.

1. Point-to-Point Messaging Domain

2. Publisher/Subscriber Messaging Domain

1) Point-to-Point (PTP) Messaging Domain

In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM).

The Queue is responsible to hold the message until receiver is ready.

In PTP model, there is no timing dependency between sender and receiver.

2) Publisher/Subscriber (Pub/Sub) Messaging Domain

In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Here, Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.

In PTP model, there is timing dependency between publisher and subscriber.


JMS Programming Model

JMS Queue Example

To develop JMS queue example, you need to install any application server. Here, we are
using glassfish3 server where we are creating two JNDI.

1. Create connection factory named myQueueConnectionFactory

2. Create destination resource named myQueue

After creating JNDI, create server and receiver application. You need to run server and receiver in
different console. Here, we are using eclipse IDE, it is opened in different console by default.

1) Create connection factory and destination resource

Open server admin console by the URL http://localhost:4848

Login with the username and password.


Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the
Resource Type as QueueConnectionFactory then click on ok button.

Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical
destination name then click on ok button.
2) Create sender and receiver application

Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will be
invoked when user sends message.

File: MySender.java

1. import java.io.BufferedReader;

2. import java.io.InputStreamReader;

3. import javax.naming.*;

4. import javax.jms.*;

5.

6. public class MySender {

7. public static void main(String[] args) {

8. try

9. { //Create and start connection

10. InitialContext ctx=new InitialContext();

11. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti


onFactory");

12. QueueConnection con=f.createQueueConnection();


13. con.start();

14. //2) create queue session

15. QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

16. //3) get the Queue object

17. Queue t=(Queue)ctx.lookup("myQueue");

18. //4)create QueueSender object

19. QueueSender sender=ses.createSender(t);

20. //5) create TextMessage object

21. TextMessage msg=ses.createTextMessage();

22.

23. //6) write message

24. BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

25. while(true)

26. {

27. System.out.println("Enter Msg, end to terminate:");

28. String s=b.readLine();

29. if (s.equals("end"))

30. break;

31. msg.setText(s);

32. //7) send message

33. sender.send(msg);

34. System.out.println("Message successfully sent.");

35. }

36. //8) connection close

37. con.close();

38. }catch(Exception e){System.out.println(e);}

39. }

40. }

File: MyReceiver.java

1. import javax.jms.*;

2. import javax.naming.InitialContext;
3.

4. public class MyReceiver {

5. public static void main(String[] args) {

6. try{

7. //1) Create and start connection

8. InitialContext ctx=new InitialContext();

9. QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnecti
onFactory");

10. QueueConnection con=f.createQueueConnection();

11. con.start();

12. //2) create Queue session

13. QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

14. //3) get the Queue object

15. Queue t=(Queue)ctx.lookup("myQueue");

16. //4)create QueueReceiver

17. QueueReceiver receiver=ses.createReceiver(t);

18.

19. //5) create listener object

20. MyListener listener=new MyListener();

21.

22. //6) register the listener object with receiver

23. receiver.setMessageListener(listener);

24.

25. System.out.println("Receiver1 is ready, waiting for messages...");

26. System.out.println("press Ctrl+c to shutdown...");

27. while(true){

28. Thread.sleep(1000);

29. }

30. }catch(Exception e){System.out.println(e);}

31. }

32.
33. }

File: MyListener.java

1. import javax.jms.*;

2. public class MyListener implements MessageListener {

3.

4. public void onMessage(Message m) {

5. try{

6. TextMessage msg=(TextMessage)m;

7.

8. System.out.println("following message is received:"+msg.getText());

9. }catch(JMSException e){System.out.println(e);}

10. }

11. }

Run the Receiver class first then Sender class.

JMS Topic Example

It is same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and Receiver
to Subscriber.

You need to create 2 JNDI named myTopicConnectionFactory and myTopic.

File: MySender.java

1. import java.io.BufferedReader;

2. import java.io.InputStreamReader;

3. import javax.naming.*;

4. import javax.jms.*;

5.

6. public class MySender {

7. public static void main(String[] args) {

8. try

9. { //Create and start connection

10. InitialContext ctx=new InitialContext();

11. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa


ctory");
12. TopicConnection con=f.createTopicConnection();

13. con.start();

14. //2) create queue session

15. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

16. //3) get the Topic object

17. Topic t=(Topic)ctx.lookup("myTopic");

18. //4)create TopicPublisher object

19. TopicPublisher publisher=ses.createPublisher(t);

20. //5) create TextMessage object

21. TextMessage msg=ses.createTextMessage();

22.

23. //6) write message

24. BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

25. while(true)

26. {

27. System.out.println("Enter Msg, end to terminate:");

28. String s=b.readLine();

29. if (s.equals("end"))

30. break;

31. msg.setText(s);

32. //7) send message

33. publisher.publish(msg);

34. System.out.println("Message successfully sent.");

35. }

36. //8) connection close

37. con.close();

38. }catch(Exception e){System.out.println(e);}

39. }

40. }

File: MyReceiver.java

1. import javax.jms.*;
2. import javax.naming.InitialContext;

3.

4. public class MyReceiver {

5. public static void main(String[] args) {

6. try {

7. //1) Create and start connection

8. InitialContext ctx=new InitialContext();

9. TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFa
ctory");

10. TopicConnection con=f.createTopicConnection();

11. con.start();

12. //2) create topic session

13. TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

14. //3) get the Topic object

15. Topic t=(Topic)ctx.lookup("myTopic");

16. //4)create TopicSubscriber

17. TopicSubscriber receiver=ses.createSubscriber(t);

18.

19. //5) create listener object

20. MyListener listener=new MyListener();

21.

22. //6) register the listener object with subscriber

23. receiver.setMessageListener(listener);

24.

25. System.out.println("Subscriber1 is ready, waiting for messages...");

26. System.out.println("press Ctrl+c to shutdown...");

27. while(true){

28. Thread.sleep(1000);

29. }

30. }catch(Exception e){System.out.println(e);}

31. }
32.

33. }

File: MyListener.java

1. import javax.jms.*;

2. public class MyListener implements MessageListener {

3.

4. public void onMessage(Message m) {

5. try{

6. TextMessage msg=(TextMessage)m;

7.

8. System.out.println("following message is received:"+msg.getText());

9. }catch(JMSException e){System.out.println(e);}

10. }

11. }

Message Driven Bean

A message driven bean (MDB) is a bean that contains business logic. But, it is invoked by passing the
message. So, it is like JMS Receiver.

MDB asynchronously receives the message and processes it.

A message driven bean receives message from queue or topic, so you must have the knowledge of
JMS API.

A message driven bean is like stateless session bean that encapsulates the business logic and doesn't
maintain state.

Message Driven Bean Example

To create the message driven bean, you need to declare @MessageDriven annotation and
implement MessageListener interface.

In eclipse ide, create EJB Project then create a class as given below:

File: MyListener.java
1. package com.javatpoint;

2. import javax.ejb.MessageDriven;

3. import javax.jms.*;

4.

5. @MessageDriven(mappedName="myTopic")

6. public class MyListener implements MessageListener{

7. @Override

8. public void onMessage(Message msg) {

9. TextMessage m=(TextMessage)msg;

10. try{

11. System.out.println("message received: "+m.getText());

12. }catch(Exception e){System.out.println(e);}

13. }

14. }

Export the ejb project and deploy the application.

In glassfish server, click on applications -> deploy -> select mdb jar file by Choose File -> OK.

Now send the message using JMS that is covered in the previous page.
Entity Bean in EJB 3.x

Entity bean represents the persistent data stored in the database. It is a server-side component.

In EJB 2.x, there was two types of entity beans: bean managed persistence (BMP) and container
managed persistence (CMP).

Since EJB 3.x, it is deprecated and replaced by JPA (Java Persistence API) that is covered in the
hibernate tutorial.

In hibernate tutorial, there are given hibernate with annotation examples where we are using JPA
annotations. The JPA with Hibernate is widely used today.

EJB Architecture Java

Java beans incorporate a set of objects into one accessible object that can be accessed easily from
any application. This single accessible object is maintainable, customizable, and reusable. The
setter/getter method and the single public constructor are used to govern that single accessible
object. We can update and read the value of any variable of any object by using the setter and getter,
respectively.

The EJB stands for Enterprise Java beans that is a server-based architecture that follows the
specifications and requirements of the enterprise environment. EJB is conceptually based on the Java
RMI(Remote Method Invocation) specification. In EJB, the beans are run in a container having four-
tier architecture. This architecture consists of four layers, i.e., Client layer, Web layer, Application
layer, and Data layer.

Architecture

The EJB architecture has two main layers, i.e., Application Server and EJB Container, based on which
the EJB architecture exist. The graphical representation of the EJB architecture is given below.
In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed. In
order to deploy the containers, it requires the Application server.

Application Server

In the EJB architecture, the Application server is the outermost layer that holds or contains the
Container to be deployed. The application layer plays an important role in executing the application
developed using the beans. It provides the necessary environment to execute those applications.
Some most popular application servers are Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-
finish. The main tasks of the application server are:

1. Manage Interfaces

2. Execution of the processes

3. Connecting to the database

4. Manage other resources.

Container

In EJB architecture, the Container is the second outermost layer. It is a very important layer for
enterprise beans that are contained in it. For the enterprise bean, the Container provides various
supporting services, which are as follows:

o It provides support for transactional services such as registering the objects, assign remote
interfaces, purge the instances.

o It provides support for monitoring the object's activities and coordinating distributed
components.

o It provides support for security services.

o It provides support for the pooling of resources.

o It provides support for managing the Life-cycle of beans and their concurrency.

o It provides support to concentrate on business logic.


Beans

Java beans of the enterprise are installed in the Container in the same way as a Plain old java object
(POJO) is installed and registered to the Container. For developing secured, large scale and robust
business applications, beans provide business logic.

Types of EJB

There are three types of Enterprise Java Beans or EJB available, which are as follows:

1. Stateless Enterprise Java Beans

2. Stateful Enterprise Java Beans

3. Message-driven Enterprise Java Beans

Stateless EJB

In order to implement the stateless business logic, the stateless EJBs are primarily used. Storing a
user's physical address into an inventory system's database is an example of the stateless EJB. In
addition, a stateless bean would be perfect for this type of business logic because it is not necessary
to have more than two forms on the user interface at all stages of the transaction.

StatelessBeanExample.java

1. package com.javatpoint.ejbarchitecture;

2. import javax.ejb.Stateless;

3.

4. @Stateless

5. public class StatelessBeanExample {

6. }

Stateful EJB

The Stateful EJB is just opposite to the Stateless EJB. The Stateful EJBs are used when we have to
maintain the state of the application on the backend during the user session. The shopping cart of an
online shopping application is an example of the Stateful EJB. In order to achieve such application,
we will use the following steps:

1. We will create the stateful session bean.

2. After that, for temporarily storing the selected products that are within the user session on
the backend, we have to create a global variable collection of type products.

3. Next, we will create a method through which we will add all the selected products to the
collection that we create in the previous step.

4. We also create a method through which we will remove the product from the collection.

5. In the end, we will create a checkout method for the selected products to process.

StatelessBeanExample.java
1. package com.javatpoint.ejbarchitecture;

2. import javax.ejb.Stateful;

3.

4. @Stateful

5. public class StatelessBeanExample {

6. }

Message-driven EJB

Another special type of EJB that is used for sending and receiving messages from message brokers
implements the JMS specification. The systems based on the broker are loosely coupled. The
components that communicate through the broker have the advantage of not waiting for one
request to finish before submitting another request because the broker by nature is asynchronous.

MessageDrivenBeanExample.java

1. package com.javatpoint.ejbarchitecture;

2. import javax.ejb.MessageDriven;

3. import javax.jms.MessageListener;

4. import javax.jms.Message;

5. import javax.ejb.ActivationConfigProperty;

6.

7. @MessageDriven(mappedName = "jms/Queue", activationConfig = {

8. @ActivationConfigProperty(propertyName = "reciverType", propertyValue = "javax.j


ms.Queue"),

9. @ActivationConfigProperty(propertyName = "reciver", propertyValue = "java:/


queue/testqueue")

10. })

11. public class MessageDrivenBeanExample implements MessageListener {

12.

13. public MessageDrivenBeanExample() {

14. }

15. public void onMessage(Message message) {

16. System.out.println("Message received successfully .");

17. }

18. }

Difference b/w EJB and JB


These are the following differences between EJB and JB:

S.No. EJB JB

EJB is not visible because it runs as a


1. JB is visible.
remote.

EJB can execute on both the clien


2. EJB is executed on the server-side.
side and the server-side.

For interpreting the bean's


EJB works with an external builder
3. functionality, EJB uses its external
tool or its IDE.
interface.

EJB uses the technology of By using generic components crea


4. components but cannot build or by Java beans, it is able to build a
extend it over beans. and application.

It has no property editor, customizer,


and bean information classes. It has
It has property editors, customize
5. only information about what is
and bean information classes.
provided by the deployment
descriptor.

6. It supports transactions. It doesn't support transactions.

7. Three types of EJB possible. No types.

Types of EJB

EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It encapsulates the
business logic of an application. It is a specification for developing a distributed business application
on the Java platform. There are three types of EJBs: Session Bean, Entity Bean, and Message-Driven
Bean. In this section, we will discuss all types of EJB in detail.
Let's discuss one by one in detail.

Session Bean

The bean sprout business idea that can be systematically used by customer, remote, and web service.
When a client wants to use an application distributed on a server, then the client uses session bean
methods. This session bean provides services to customers, protecting them from complex problems
by performing business operations within the server.

To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by executing
business errands inside the worker. Remember that session beans are not persistence.

There are two types of session beans:

o Stateless Session Beans

o Stateful Session Beans

o Singleton Session Beans

Stateless Session Beans

A stateless session bean doesn't keep a conversational state with the customer or client. When a
client invokes the methods for a stateless bean, the bean's instance variable may contain a state
explicitly to that client however only for the span of the invocation.
At the point when the method has finished, the client explicit state should not be held. However, the
client may change the state of instance variable presented in pooled stateless beans, and this state is
held over to the following invocation of the pooled stateless bean.

Besides this, during the invocation of the method, all instances of a stateless bean are the same,
permitting the EJB container to assign an instance to any client. Therefore, the state of a stateless
session bean should apply across all clients. It can be implemented in a web-services.

Since they can maintain various customers, stateless session beans can offer better adaptability for
applications that require large numbers of clients. Ordinarily, an application requires fewer stateless
session beans than stateful session beans to support the same number of clients.

To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.

Advertisement

o The state of the bean has no information or data for a particular client.

o In a private method invocation, the bean performs a generic task for all clients.

o The bean implements a web service.

Stateful Session Beans

A stateful session bean is the same as an interactive session. The state of an object comprises the
values of its instance variables. In a stateful session bean, the instance variables denote the state of a
unique client/bean session. Since, the client interacts with its bean. The state is usually called
the conversational state. It maintains the state of a client across multiple requests. So, we cannot
implement it in the web services because it cannot be shared. When the client terminates the
session, it is no longer associated with the client.
The state is held for the span of the client/bean session. In case if the client eliminates the bean, the
session closes and the state is omitted. This transient nature of the state isn't an issue, because the
interaction between the client and the beans ends. So, it is not required to hold the state.

Stateful session beans should be used, if any of the following conditions are valid:

o The bean's state denotes the alliance between the bean and a particular client.

o The bean needs to hold data about the customer across method invocations.

o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.

o In the background, the bean deals with the workstream of a few enterprise beans.

Note: Stateless and stateful both session beans are not persistent.

Singleton Session Beans

A singleton session bean maintains one instance per application and the instance exists for the
lifecycle of the application. It offers the same functionality as the stateless session beans. But the
only difference is that there is only one singleton session bean per application while in the stateless
session bean a pool of beans is used.

From that pool, any of the session beans may respond to the client. We can implement it in the web-
service endpoints. It takes care of the state but does not hold the state if unexpected crashes or
shutdown occur. It can be used if we want to perform cleanup tasks on closing the application or shut
down as well. It is because it operates throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:

o The state of the bean must be shared across the application.

o A single enterprise bean should be accessed by multiple threads concurrently.

o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.

o The bean implements a web service.

Entity Bean

An entity bean is an unpredictable business substance. It models a business substance or models


different activities inside a business interaction. It is used to encourage business benefits that include
data and calculations on that data. It can deal with various, needy, diligent articles in playing out its
essential assignments. A substance bean is a far-off object that oversees steady information and
performs complex business rationale. It can be extraordinarily distinguished by an essential key.

Advertisement
It is a far-off object that oversees steady information, performs complex business rationale, possibly
utilizes a few ward Java protests, and can be remarkably distinguished by an essential key. It
ordinarily coarse-grained determined items since they use steady information put away inside a few
fine-grained relentless Java objects. Element beans are diligent on the grounds that they do endure a
worker crash or an organization's disappointment.

Every entity bean has a persistence identity that is associated with it. It means that it comprises a
unique identity that can be fetched if we have a primary key. The type for the unique key is defined
by the bean provider. A client can retrieve the entity bean if the primary has been misplaced. If the
bean is not available, the EJB container first, instantiates the bean and then re-populates the data for
the client.

The diligence for entity bean information is given both to saving state when the bean is passivated
and for improving the state when a failover has detected. It can endure in light of the fact that the
information is put away determinedly by the holder in some type of information stockpiling
framework, like a data set.

Advertisement

Entity beans persist business data by using the following two methods:

o Bean-Managed Persistence (BMP)

o Container-Managed Persistence (CMP)

Bean Managed Persistence

Bean-managed persistence is more complicated in comparison to container-managed persistence.


Because it allows us to write the persistence logic into the bean class, explicitly. In order to write the
persistence handling code into the bean class, we must know the type of database that is being used
and how fields of the bean class are mapped to the database. Therefore, it provides more flexibility
between the database and the bean instance.

It can be used as an alternative to CMP. If the deployment tools are incompatible for mapping the
bean instance's state to the database. The disadvantage of BMP is that more work is required to
define the bean and it ties the bean to a specific database type and structure.

Container-Managed Persistence

In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not produce
information base access articulations with the proficiency of a programmer.
Unlike BMP, CMP does not allow us to write database access calls in the methods of the entity bean
class. It is because the persistence is handled by the container at run-time. The following two things
are required to support the CMP:

o Mapping: It denotes that how to map an entity bean to a resource.

o Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.

Note: Entity bean has been replaced with Java persistence API.

Message-Driven Bean (MDB)

MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous communication
using a JMS message listener. An advantage of using MDB is that it allows us to use the asynchronous
nature of a JMS listener. We can implement message-driven beans with Oracle JMS (Java Messaging
Service).

There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each incoming
message is handled by a bean that is invoked by the container. Note that no object invokes an MDB
directly. All invocation for MDB originates from the container. When the container invokes the MDB,
it can invoke other EJBs or Java objects to continue the request.

It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests. EJB has the following benefits over the JMS are as follows:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.

o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.

o The message ACK mode is specified.

Advertisement

The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination
(i.e. queue or topic). While using MDB ensure that it is configured and installed properly. It interacts
with JMS and the JMS installed on the Oracle database. The database retains queue or topic. The
following figure depicts how MDB interacts with the JMS destination.

The working of MDB is as follows:

o MDB creates and opens a JMS connection to the database by using the data source (JMS
resource provider). The JDBC driver is used to facilitate the JMS connection.

o A JMS session over the JMS connection is opened by the MDB.

o If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the message
for the MDB.

Note that it does not handle the requests that are requested by the clients instead it handles
requests that are placed into a queue.

MDB implements the javax.ejb.MessageDriverBean interface and inherits the


javax.jms.MessageListener class that provides the following methods:

Method Description
The container dequeues a message from the JMS queu
associated with this MDB and gives it to this instance b
onMessage(msg)
invoking this method. This method must have an
implementation for handling the message appropriate

After the bean is created, the setMessageDrivenConte


setMessageDrivenContext(ctx) method is invoked. This method is similar to the EJB
setSessionContext and setEntityContext methods.

This method is used just like the stateless session bean


ejbCreate method. No initialization should be done in
ejbCreate()
method. However, any resources that you allocate with
this method will exist for this object.

Delete any resources allocated within the ejbCreate


ejbRemove()
method.

Difference Between Session and Entity Bean

The following table depicts the key differences between session bean and entity bean.

Basis of Comparison Session Bean Entity Bean

It has no primary key. It is used to It has a primary key that allows us


Primary Key identify and retrieve specific bean find instances and can be shared
instances. more than one client.

Stateless/ Stateful It may be stateful or stateless. It is stateful.

Span It is relatively short-lived. It is relatively long-lived.

It represents a single conversation It encapsulates persistence busine


Performance
with a client. data.

It is created and used by a single


Accessibility It may be shared by multiple clien
client.

It is not recoverable in case if EJB It is recoverable if any failure has


Recovery
server fails. So, it may be destroyed. occurred.

Persistence of Data It persists data only for the span of the Persistence beyond the life of a cl
conversation with the client. instance. Persistence can be conta
managed or bean-managed.

Remote Interface It extends javax.ejb.EJBObject. It extends javax.ejb.EJBObject.

Home Interface It extends javax.ejb.EJBHome. It extends javax.ejb.EJBHome.

Bean Class It extends javax.ejb.EJBSessionBean. It extends javax.ejb.EJBEntityBean

EJB Container

EJB is a server-side software element that summarizes the business logic of an


application. Enterprise Java Beans web repository yields a runtime domain for web-related software
elements including computer reliability, Java Servlet Lifecycle (JSL) management, transaction
procedure, and other web services.

What is an EJB container?

EJB container is a server-side component that comprises the business logic. It offers local and remote
access to the enterprise beans. In other words, we can say that it provides a runtime environment for
EJB applications within the application server. A single EJB container can have one or more EJB
modules. It acts as an intermediate action between business logic and enterprise application. The
following figure depicts the structure of the EJB container.

The typical behavior envisioned by the Java EE specification is that a developer writes an Enterprise
JavaBean, a simple component, and the EJB container adds the necessary infrastructure for
communications, transactions, and data access. It turns the business logic into something that
executes.

In addition, the EJB container provides lifecycle management for the component to ensure that its
creation, usage, and destruction are both efficient and in accord with the specification.

When the EJB container is started, it has, at its highest level, the EJBContainerImpl class as its
controller. It is a subclass of the generic ContainerImpl class. EJBContainerImpl implements the
EJBContainer service interface and has listeners for changes to the deployed application modules and
other parts of the environment.

Let's see the inheritance dependencies, methods, and interfaces that define the EJB container.

But if we look at the WsComponent interface, we can see some key methods that explain how the
components, and therefore the container, are controlled by the WAS runtime environment. The
ContainerImpl class is a subclass of the ComponentImpl class, so it can be treated like any other
component by the loadComponents calls of the outer container that initializes it. It is how the base
server starts, controls, and interacts with the EJB container.

It is responsible for creating the enterprise bean, binding the enterprise bean to the naming service
so that other application components can access the enterprise bean, ensuring only authorized
clients have access to the enterprise bean's methods, saving the bean's state to persistent storage,
caching the state of the bean, and activating or passivating the bean when necessary.

The EJB Container Implementation Class

The EJBContainerImpl class is a complex class with many dependencies, as shown in the following
figure. Some of the dependencies are structural and inheritance-related, and some are dynamic and
collaborative in nature.
Using reflection, we can see the interfaces that the EJBContainerImpl class uses.

Advertisement

What does an EJB container do?

EJB container performs the following tasks:

o Instantiate beans on demand

o Manages a pool of bean instances

o Manage Transactions

o Loads/ saves bean data from/to a database

o Handles Security

o Provides other System Services


EJB Container Services

EJB Container provides the following valuable services for enterprise application development.

o Transaction support (start, rollback, and commit)

o Security Model

o Persistence Support

o Timing Services and Job Scheduling

o Messaging

o Remote Access

o Distribution

o Web-services

o Component Pooling

o Component Life-cycle

o Interceptors

o Asynchronous Interactions

o Thread-safety and Concurrency Control

EJB Interview Questions

There is given EJB interview questions and answers that have been asked in many companies. Let's see the list of top E
interview questions.
1) What is EJB?

EJB stands for Enterprise Java Bean. It is a server-side component to develop scalable, robust and secured enterprise
applications in java. More details...

2) What are the types of Enterprise Bean?

There are three types of enterprise bean in java.

1. Session Bean

2. Message Driven Bean

3. Entity Bean

More details...

3) What is session bean?

Session Bean encapsulates business logic. It can be invoked by local, remote or web service client.

Backward Skip 10sPlay VideoForward Skip 10s

There are 3 types of session bean.

1. Stateless Session Bean

2. Stateful Session Bean

3. Singleton Session Bean

More details...

4) What is stateless session bean?

A Stateless session bean is a business object that doesn't maintain the conversational state with the client. More deta

5) Write down the steps for the creation of stateless EJB.

o Create a local interface.

o The interface is to be used by the client application.

o In case the EJB client environment is the same, use @Local annotation.

o In case the EJB client environment is different, use @Remote annotation.

o Create a stateful session bean.

o To signify a stateful bean, use @Stateful annotation.


6) What is stateful session bean?

A Stateful session bean is a business object that maintains the conversational state with the client. More details...

7) What is singleton session bean?

Singleton session bean is instantiated only once for the application. It exists for the life cycle of the application.

8) What is JMS?

Java Message Service is a messaging service to create, send and receive messages asynchronously. More details...

9) What are the advantages of JMS?

o Asynchronous

o Reliable

More details...

10) What is PTP model?

In Point to Point model, one message is delivered to one receiver only. Here, Queue is used as a message-oriented
middleware. More details...

11) What is Pub/Sub model?

In the Publisher/Subscriber model, one message is delivered to all subscribers. Here, Topic is used as a message-orient
middleware. More details...

12) What is MDB?

Message Driven Bean (MDB) encapsulates business logic. It is invoked by passing the message. It is like JMS receiver. M
details...

13) What is Entity Bean?

Entity Bean is a server-side component that represents the persistent data. Since EJB 3.x, it is replaced by JPA. More d

14) What is Session Facade?

Session Facade is a design pattern to access enterprise bean through the local interface. It abstracts the business objec
interactions and provides a service layer. It makes the performance fast over the network.

15) List some key actors in persistence API.

Some of the key actors in persistence API are:

o Entity

o EntityManager

o Persistence unit

o Data source

16) List down the steps for the demonstration of EJP persistence mechanism.

o Create a database table

o Create entity classes for the table

o Create persistent unit and data source

o Create a stateless EJB

o Update stateless EJBM

o Console based application accesses the stateless EJB.

17) Name the attributes of javax.ejb.Stateful.

o Name

o mappedName

o Description

18) Name the attributes of javax.ejb.EJB.

beanInterface

beanName

mappedName

19) Mention the three levels for applying interceptor methods.

o Default

o Class
o Method

20 Mention the Java types that can be mapped using the @Lob annotation.

o java.sql.Blob

o String

o byte[]

o java.sql.Clob

o Serializable Object

21) Name the ACID properties of a transaction.

o Atomic

o Consistent

o Isolated

o Durable

Java Basics Interview Questions Java OOPs Interview Questions

Java Multithreading Interview Questions Java String & Exception Interview Questions

Java Collection Interview Questions JDBC Interview Questions

Servlet Interview Questions JSP Interview Questions

Spring Interview Questions Hibernate Interview Questions

PL/SQL Interview Questions SQL Interview Questions

Oracle Interview Questions Android Interview Questions

SQL Server Interview Questions MySQL Interview Questions

Latest Courses

You might also like