Enterprise JavaBeans(EJB)

28
Enterprise JavaBeans (EJBs) ID2212 Network Programming with Java Lecture 12 Vladimir Vlassov KTH/ICT/SCS HT 2010

description

Enterprise JavaBeans(EJB)

Transcript of Enterprise JavaBeans(EJB)

Page 1: Enterprise JavaBeans(EJB)

Enterprise JavaBeans (EJBs)

ID2212 Network Programming with Java

Lecture 12

Vladimir Vlassov

KTH/ICT/SCS

HT 2010

Page 2: Enterprise JavaBeans(EJB)

Outline

• Enterprise JavaBeans (EJB)

– Session

– Message-Driven

• Example: Bank Account Application – to be

Lecture 12: Enterprise JavaBeans (EJBs) 2

• Example: Bank Account Application – to be

considered at Exercise 4 (see slides of Exercise 4)

Page 3: Enterprise JavaBeans(EJB)

Enterprise JavaBeans (EJB)

javax.ejb

home page:

http://www.oracle.com/technetwork/java/index-jsp-140203.html

Page 4: Enterprise JavaBeans(EJB)

Enterprise JavaBeans (EJB)

• An EJB is server-side components that expose methods for performing application logic

• EJB 3– Session Beans (stateless and stateful) represent actions (a single

action, a session)• Performs a task for a client; optionally may implement a web service

Lecture 12: Enterprise JavaBeans (EJBs) 4

• Performs a task for a client; optionally may implement a web service

– Message-driven Beans• Acts as a listener for a particular messaging type, such as the Java

Message Service (JMS)

• EJB 2– Session Beans (stateless and stateful)

– Entity Beans represent persistent stateful entity (e.g. account, person, customer). An entity bean – a row in a database

– Entity beans have been replaced by Java Persistence API entities.

Page 5: Enterprise JavaBeans(EJB)

Session Beans

• Business process objects, for example, business

logic, workflow and similar

• A session bean represents a single client inside the

Application Server.

Lecture 12: Enterprise JavaBeans (EJBs) 5

Application Server.

– Used only by one client at a time

– Lives for the session (or lifetime) of the calling client

• Two kind of sessions EJBs

– Stateless session EJBs

– Stateful session EJB

Page 6: Enterprise JavaBeans(EJB)

A Stateless Session Bean

• The bean class is annotated as @Stateless

• Accommodates only a single request.

• Does not maintain a conversational state with the client. – May contain a state, but only for the duration of an invocation by a

client.

– When the method invocation is finished, the state is no longer

Lecture 12: Enterprise JavaBeans (EJBs) 6

– When the method invocation is finished, the state is no longer retained

• A pool of beans– All instances of a stateless bean are equivalent

– Can offer better scalability

– May offer better performance (compare to stateful beans) as the state is not written to the secondary storage

• Example: A currency converter

Page 7: Enterprise JavaBeans(EJB)

A stateful Session Bean

• The bean class is annotated as @Stateful

• Spans multiple client requests or transactions and retains state on behalf of the individual client.

• One bean instance per client.

Lecture 12: Enterprise JavaBeans (EJBs) 7

– Values of instance variables represent the state of a unique client-bean session.

• A.k.a. the conversational state

– If the client removes the bean or terminates, the session ends and the state disappears.

• Example: A shopping cart

Page 8: Enterprise JavaBeans(EJB)

Business Interface of a Session Bean

• A client uses a session bean through the methods

of the bean's business interface.

– The interface includes the business methods exposed by

the bean’s class

Lecture 12: Enterprise JavaBeans (EJBs) 8

– The bean class implements the business interface

• A client of a session bean can be a web

component, an application client, or another EJB

Page 9: Enterprise JavaBeans(EJB)

Business Interface of a Session Bean

(contd)• The client gets a reference to the session bean’s interface either through

injection or JNDI lookup

• For example: The AdderServlet gets the reference to the remote interface of the AdderBean

@WebServlet(name = "AdderServlet", urlPatterns = {"/AdderServlet"})

public class AdderServlet extends HttpServlet {

@EJB

private AdderRemote adder;

Lecture 12: Enterprise JavaBeans (EJBs) 9

private AdderRemote adder;

//private AdderRemote adder = lookupAdderBeanRemote(); // through lookup

private AdderRemote lookupAdderBeanRemote() {

try {

Context c = new InitialContext();

return (AdderRemote) c.lookup(

"java:global/Adder/Adder-ejb/AdderBean!adder.AdderRemote");

} catch (NamingException ne) {

Logger.getLogger(getClass().getName()).log(Level.SEVERE,

"exception caught", ne);

throw new RuntimeException(ne);

}

}

Page 10: Enterprise JavaBeans(EJB)

Business Interface Design Options

• Local interface for local clients on the same JVM

• Remote interface for remote clients on different JVM• Remote interface obeys the rules of Java RMI.

• No-interface view (EJB 3.1) for local clients

– All public methods of the bean class are automatically exposed to the

Lecture 12: Enterprise JavaBeans (EJBs) 10

– All public methods of the bean class are automatically exposed to the client

– Does not require a separate interface; there is no the implements clause

– The same behavior as the EJB 3.0 local interface view

– Simplifies programming

• Web Services interface

– Exposing business methods as Web Services

– Stateless session beans can be invoked over SOAP/HTTP

Page 11: Enterprise JavaBeans(EJB)

A Session EJB with a Remote Interface

• An interface for remote access

• Annotate the interface with the @Remote annotation:

@Remote

public interface InterfaceName {...

}

Lecture 12: Enterprise JavaBeans (EJBs) 11

}

• Annotate the bean class with @Remote, specifying the business interface(s):

@Remote(InterfaceName.class)

public class BeanName implements InterfaceName {...

}

Page 12: Enterprise JavaBeans(EJB)

A Session EJB with a Local Interface

• An interface for local access

• Annotate the interface with the @Local annotation:

@Local

public interface InterfaceName {...

}

Lecture 12: Enterprise JavaBeans (EJBs) 12

}

• Annotate the bean class with @Local, specifying the business interface(s):

@Local (InterfaceName.class)

public class BeanName implements InterfaceName {...

}

Page 13: Enterprise JavaBeans(EJB)

Deciding on Remote or Local Access

• Tight or loose coupling of related beans:

– Tightly coupled beans depend on one another, and they

are good candidates for local access.

• Type of client:

Lecture 12: Enterprise JavaBeans (EJBs) 13

• Type of client:

– For application clients, the EJB should allow remote

access.

– For web components or other EJBs, type of access

depends on distribution of components

Page 14: Enterprise JavaBeans(EJB)

Deciding on Remote or Local Access

(contd)

• Component distribution:

– Server-side components can be distributed among

multiple machines for scalability.

– Web components may run on a different server than

EJBs. EJBs should allow remote access.

Lecture 12: Enterprise JavaBeans (EJBs) 14

EJBs. EJBs should allow remote access.

• Performance:

– Remote calls may be slower than local calls. However,

distribution of components among different servers

may improve the application's overall performance.

Page 15: Enterprise JavaBeans(EJB)

Contents of an Enterprise Bean

• Business Interfaces

– The business interface defines

the methods implemented by

the enterprise bean class.

• EJB class

– Implements the methods

• The files are packaged into an

EJB JAR file

• Structure of an EJB JAR:

Lecture 12: Enterprise JavaBeans (EJBs) 15

– Implements the methods

defined in the business

interfaces.

• Helper classes:

– Other classes needed by the

enterprise bean class, such as

exception and utility classes.

Page 16: Enterprise JavaBeans(EJB)

EJB Naming Convention

Item Syntax Example

EJB name <name>Bean AdderBean

EJB class <name>Bean AdderBean

Lecture 12: Enterprise JavaBeans (EJBs) 16

EJB class <name>Bean AdderBean

Business interface <name> Adder

(AdderRemote

AdderLocal)

Page 17: Enterprise JavaBeans(EJB)

Example: Adder Service

• A client-server application

– A user enters an integer number via an adder client – HTML form or an applet – and gets a sum accumulated at the Adder server.

• The Adder server includes:

– The Adder servlet (also considered on Lecture 10)

– The Adder EBJ (session, stateful) that accumulates a sum of integers

Lecture 12: Enterprise JavaBeans (EJBs) 17

– The Adder EBJ (session, stateful) that accumulates a sum of integers entered by a user, and returns the sum on request

• The adder servlet receives the client HTTP request and serves as an interface to the adder EJB

Web BrowserWeb Browser

HTML form clientHTML form client

Adder Servlet Adder EJBAdder EJB

Application ServerApplication Serveradd(int)

int getTotal()

Web container (servlet engine) EJB container

Page 18: Enterprise JavaBeans(EJB)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Client

• An HTML Form in a Web page (index.jsp) in a browser

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Initial page for AdderServlet</title>

</head>

<body>

<h1>Initial page for AdderServlet</h1>

<form action="AdderServlet">

Please enter an integer:

<input type="text" name="inputString" value="" />

<br>

<input type="submit" />

</form>

</body>

</html>Lecture 12: Enterprise JavaBeans (EJBs) 18

Page 19: Enterprise JavaBeans(EJB)

Adder

Servlet• The Adder Servlet

is a client of the

Adder EJB

– The servlet is

also considered

in Lecture 10.

package adder;

import java.io.*;

import java.util.logging.*;

import javax.ejb.EJB;

import javax.naming.*;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet(name = "AdderServlet", urlPatterns = {"/AdderServlet"})

public class AdderServlet extends HttpServlet {

@EJB

private AdderRemote adder;

//private AdderRemote adder = lookupAdderBeanRemote();

private AdderRemote lookupAdderBeanRemote() {

try {

Lecture 12: Enterprise JavaBeans (EJBs) 19

try {

Context c = new InitialContext();

return (AdderRemote) c.lookup("java:global/Adder/Adder-ejb/AdderBean!adder.AdderRemote");

} catch (NamingException ne) {

Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);

throw new RuntimeException(ne);

}

}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

Page 20: Enterprise JavaBeans(EJB)

Adder

Servlet

(contd)

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

String inputString = request.getParameter("inputString");

Integer inputNumber = new Integer(inputString);

adder.add(inputNumber.intValue());

int total = adder.getTotal();

generatePage(out, total);

} finally {

out.close();

}

}

private void generatePage(PrintWriter out, int total) {

out.println("<html>");

Lecture 12: Enterprise JavaBeans (EJBs) 20

out.println("<html>");

out.println("<head>");

out.println("<title>Input for AdderServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("The running total is: " + String.valueOf(total));

out.println("<p>");

out.println("<form method = get action=\"AdderServlet\">");

out.println("Please enter an integer:");

out.println("<input type=text name=\"inputString\">");

out.println("<p>");

out.println("<input type=submit>");

out.println("</form>");

out.println("</body>");

out.println("</html>");

}

}

Page 21: Enterprise JavaBeans(EJB)

Adder EJB (Session, Stateful)

• Session

– Interface operations:

void add (int number)

int getTotal()

Lecture 12: Enterprise JavaBeans (EJBs) 21

int getTotal()

• Stateful

– private int total; // state of the bean

Page 22: Enterprise JavaBeans(EJB)

Adder EJB (contd)

• Bean’s Interfacepackage adder;

import javax.ejb.Remote;

@Remote

public interface AdderRemote {

void add(int number);

int getTotal();

}

Lecture 12: Enterprise JavaBeans (EJBs) 22

• Bean’s classpackage adder;

import javax.ejb.Stateful;

@Stateful

public class AdderBean implements AdderRemote {

private int total = 0;

public void add(int number) {

total += number;

}

public int getTotal() {

return total;

}

}

Page 23: Enterprise JavaBeans(EJB)

AdderServlet Gets a Reference to AdderBean’s

Interface

• Either through injection (as shown below) or lookup (commented)

@WebServlet(name = "AdderServlet", urlPatterns = {"/AdderServlet"})

public class AdderServlet extends HttpServlet {

@EJB

private AdderRemote adder;

Lecture 12: Enterprise JavaBeans (EJBs) 23

private AdderRemote adder;

//private AdderRemote adder = lookupAdderBeanRemote();

private AdderRemote lookupAdderBeanRemote() {

try {

Context c = new InitialContext();

return (AdderRemote) c.lookup(

"java:global/Adder/Adder-ejb/AdderBean!adder.AdderRemote");

} catch (NamingException ne) {

Logger.getLogger(getClass().getName()).log(Level.SEVERE,

"exception caught", ne);

throw new RuntimeException(ne);

}

}

Page 24: Enterprise JavaBeans(EJB)

Message-Driven Beans

• A message-driven bean is an EJB that allows Java EE applications to process messages asynchronously. – Normally acts as a JMS message listener.

• Defference between m-d beans and session beans

Lecture 12: Enterprise JavaBeans (EJBs) 24

– Clients do not access m-d beans through interfaces;

– Unlike a session bean, a m-d bean has only a bean class.

• A m-d bean resembles a stateless session bean – M-d bean instances retain no data or conversational state for a

specific client;

– All instances of a m-d bean are equivalent;

– A single m-d bean can process messages from multiple clients.

Page 25: Enterprise JavaBeans(EJB)

Features of Message-Driven EJBs

• Stateless.

• Execute upon receipt of a single client message.

• Invoked asynchronously.

• Relatively short-lived.

Lecture 12: Enterprise JavaBeans (EJBs) 25

• Relatively short-lived.

• Do not represent directly shared data in the

database, but can access and update this data.

• Can be transaction-aware.

Page 26: Enterprise JavaBeans(EJB)

Client Interaction with a Message-

Driven Bean• A client interacts with a m-d bean through JMS by sending messages

to the destination for which the message-driven bean class is the JMS message listener.

• An m-d bean’s class is annotated @MessageDriven with a name of the bean’s destination, e.g.

Lecture 12: Enterprise JavaBeans (EJBs) 26

the bean’s destination, e.g.

@MessageDriven(mappedName = "jms/Queue")

• A m-d bean's destination is assigned during deployment by using Application Server resources control panel.

• When a message arrives, the container calls the message-driven bean's onMessage method to process the message.

Page 27: Enterprise JavaBeans(EJB)

Example:

A Message-

Driven

Bean

package mdbean;

import java.io.IOException;

import java.util.logging.Level;

import javax.ejb.*;

import javax.jms.*;

import java.util.logging.*;

import javax.annotation.Resource;

@MessageDriven(mappedName = "jms/Queue")

public class MDBean implements MessageListener {

@Resource

private MessageDrivenContext context;

static final Logger logger = Logger.getLogger("SimpleMessageBean");

private static FileHandler fh;

public MDBean() {

try {

fh = new FileHandler("D:/home/vlad/logs/mylog.txt");

logger.addHandler(fh);

} catch (IOException ex) {

Logger.getLogger(MDBean.class.getName()).log(Level.SEVERE, null, ex);

Lecture 12: Enterprise JavaBeans (EJBs) 27

Logger.getLogger(MDBean.class.getName()).log(Level.SEVERE, null, ex);

} catch (SecurityException ex) {

Logger.getLogger(MDBean.class.getName()).log(Level.SEVERE, null, ex);

}

}

public void onMessage(Message message) {

try {

if (message instanceof TextMessage) {

logger.info("MDBean: Message received: " +

((TextMessage) message).getText());

}

} catch (JMSException ex) {

ex.printStackTrace();

context.setRollbackOnly();

}

}

}

Page 28: Enterprise JavaBeans(EJB)

Life Cycles of EJBs

• Stateful session bean • Message-driven bean

Lecture 12: Enterprise JavaBeans (EJBs) 28

• Stateless session bean

• During the bean’s lifetime, the EJB Container

invokes methods annotated

@PostConstruct, @PrePassivate,

@PostActivate, @PreDestroy, @Remove.

• When a client calls a business method on a

bean, which does not exists or is passive, the

container constructs the bean or activates the

bean to make it ready.