What Are EJB's?

advertisement
Enterprise Java Beans
Adam, Engels, Josh, Marc, Tim
What Are EJB’s?
• Enterprise Java Beans
• EJB: special kind of JavaBean for
performing server-side business logic
• More powerful version of the regular beans
that we’ve used in class
Where they fit in a system
EJB’s in J2EE
Three kinds of EJB’s
• Session
– associate client information with a specific
client
– both stateless and stateful versions
• Entity
– groups associated information in an abstraction
that provides transaction support
• Message Bean - rarely used, hardly supported
What is a Session Bean?
• Represents a single Client inside the J2EE
server
• one client at a time/ not persistent
• when the client terminates, the session bean
is disassociated from the client
• There are two types: Stateful and
Stateless...
Stateful
• These represent a set of interactions
between client and server.
– Example: shopping cart
• Saves information over several method
invocations.
• There is a lot of overhead associated with
using stateful beans
Stateless Beans
• A stateless bean does not save information
between method calls.
• Limited application
• Little overhead
– multiple clients can use the same bean instance
without alteration
• Example: fetch from a read-only database or send
a confirmation email for an order
Entity Beans
•
•
•
•
Associates pieces of information in a group
Accessed by multiple clients at a time
Persistent and Serializable
The container loads and stores the entity
beans in the database
• These are more similar to regular beans
More on Entity Beans
• Transactions: this is what makes an Entity
Bean special.
– Entity beans rely on the container to enforce
robust transactions
– example: Airline booking: if the flight booking
action fails, then the credit card charge action
fails, or vice versa.
Persistence in Entity Beans
• Container managed persistence
– the container controls when the bean is read
from or written to the database
• Bean managed persistence
– the bean’s implementation performs all of the
sql operations that loads, stores, and updates the
bean’s data to or from the database.
– Bean is responsible for connection allocation to
the database
Connection Pooling
• Setting up connections to the database is resource
intensive
• Connection pooling maintains a pool of database
connections for the entity beans so that the
connection is maintained when a bean finishes,
and is available for other entity beans.
• Specific to database and EJB container
implementation
Message Beans
• A message bean is an enterprise bean that allows
J2EE applications to process messages
asynchronously. It acts as a JMS message listener,
which is similar to an event listener except that it
receives messages instead of events.
• Many systems do not yet support JMS, message
bean use is currently not widespread
Using an Entity bean from a
Session bean
• An entity bean can be shared by multiple
sessions.
– This allows for data encapsulation; clients can
interact with data via session beans within
transaction boundaries.
• Can do all database interaction from session
bean as an alternative
– encapsulation is weakened
Using EJB’s
An EJB Example...
• Online Banking Application
• Demonstrates how all the component
technologies--enterprise beans, J2EE
application clients, and Web components fit
together
Online Banking Application
• Two clients:
– a J2EE application client used by administrators
to manage customers and accounts
– Web client used by customers to access account
histories and perform transactions. The clients
access the customer, account, and transaction
information maintained in a database through
enterprise beans.
Online Bank Application
Overview
Session beans used
• The online bank application has three session
beans: AccountControllerEJB,
CustomerControllerEJB, and TxControllerEJB.
These session beans provide a client's view of the
application's business logic. Hidden from the
clients are the server-side routines that implement
the business logic, access databases, manage
relationships, and perform error checking.
Entity Beans used
• For each business entity represented in our simple bank,
the bank application has a matching entity bean:
 AccountEJB, CustomerEJB, TxEJB
• The purpose of these beans is to provide an object view of
these database tables: account, customer, and tx. For each
column in a table, the corresponding entity bean has an
instance variable. Because they use bean-managed
persistence, the entity beans contain the SQL statements
that access the tables. For example, the create method of
the CustomerEJB entity bean calls the SQL INSERT
command.
Database
Security in this example
• you can protect an enterprise bean by specifying the security roles that
can access its methods In the bank application, two roles are defined-BankCustomer and BankAdmin
• BankAdmin role is allowed to perform administrative functions:
creating or removing an account, adding a customer to or removing a
customer from an account, setting a credit line, and setting an initial
balance.
• BankCustomer role is allowed to deposit, withdraw, transfer funds,
make charges and payments, and list the account's transactions. Notice
that there is no overlap in functions that users in either role can
perform
…security continued...
• Access to these functions was restricted to the appropriate
role by setting method permissions on selected methods of
the CustomerControllerEJB, AccountControllerEJB, and
TxControllerEJB enterprise beans. For example, by
allowing only users in the BankAdmin role to access the
createAccount method in the AccountControllerEJB
enterprise bean, you have denied users in the
BankCustomer role or any other role permission to create
bank accounts.
• Set method permissions in the container with the deploy
tool for each role
BankCustomer Role Mapped to Customer Group
Underlying Technologies
RMI
• RMI - Remote Method Invocation
– instead of invoking a method on another Java
object running in the same JVM, you invoke a
method in a Java object in another JVM on the
same computer or another one.
– Using an interface, RMI hides the fact that you
are invoking a method remotely
– The Remote and Home interfaces for an EJB
must be RMI interfaces
Underlying Technologies:
JNDI
• JNDI - Java Naming and Directory Interface
– JNDI provides a uniform way to access naming and
directory services
– You use JNDI to locate EJB’s and JDBC connection
pools from within your EJB container
– When a client needs to access a bean’s Home
interface, it uses JNDI to locate the Home interface.
After you locate an object, you communicate directly
with it instead of going through JNDI
– You don’t need to know much about JNDI for EJB’s
except for a few setup calls.
Underlying Technologies:
JDBC
• JDBC - Java Database Connectivity
– gives you a standard API in which to
communicate with different types of databases
– If you use CMP (Container Managed
Persistence) there’s a chance that you won’t use
JDBC at all. However there are still a few cases
in which CMP doesn’t handle all the different
ways that you can access data.
Bean Design
The Home interface
• The 2 main functions of the home interface are creating
beans and locating beans
• Only entity beans need methods to locate beans
import java.rmi.*;
import javax.ejb.*;
public interface HelloWorldHome extends EJBHome{
public MyBean create() throws RemoteException,CreateException;
MyBean findByPrimaryKey(String myEntityKey) throws
RemoteException,CreateException;
}
Bean design:
The Remote Interface
• Consists of the remote methods you can call
on a bean after the bean has been created
and located.
import java.rmi.*;
public interface HelloWorld{
public String getGreeting() throws RemoteException;
}
Bean Design
Bean Implementation
•
•
•
import java.rmi.*;
import java.util.*;
import javax.ejb.*;
•
•
•
public class HelloWorldImpl implements SessionBean{
protected String greeting;
private SessionContext context;
•
•
/** An EJB must have a public, parameterless constructor */
public HelloWorldSessionImpl(){}
•
•
•
•
•
/** Called by the EJB container when a client calls the create() method in
the home interface */
public void ejbCreate() throws CreateException{
greeting = "Hello World!";
}
•
•
•
•
/** Returns the session's greeting */
public String getGreeting(){
return greeting;
}
/** Called by the EJB container to wake this session bean up after it
has been put to sleep with the ejbPassivate method. */
public void ejbActivate(){}
public void ejbPassivate(){}
public void ejbRemove(){}
/** Called by the EJB container to set this session's context */
public void setSessionContext(SessionContext aContext) {
context = aContext;
}
}
Bean Design
Client to access bean
•
•
•
import java.util.*;
import javax.naming.*;
import javax.rmi.*;
•
•
•
•
•
public class TestHello{
public static void main(String[] args) {
try{
/** Creates a JNDI naming context for location objects */
Context context = new InitialContext();
•
•
•
•
•
•
•
•
•
•
•
•
/** Asks the context to locate an object named "HelloWorld" and expects the
object to implement the HelloWorldSessionHome interface */
HelloWorldSessionHome home = (HelloWorldSessionHome)portableRemoteObject.narrow(
context.lookup("HelloWorld"),HelloWorldSessionHome.class);
/** Asks the Home interface to create a new session bean */
HelloWorldSession session = (HelloWorldSession) home.create();
System.out.println(session.getGreeting());
/** Destroy this session */
session.remove();
} catch (Exception exc){exc.printStackTrace()}
}
}
Some Restrictions
• EJB’s cannot
– create or manage threads
– access files using java.io
– create a ServerSocket or change the socket and stream
handler factories
– load a native library
– use the AWT to interact with the user
These restrictions keep EJB’s from making too many assumptions or
interfering with its environment.
OpenEJB
• OpenEJB is an open source EJB container
and EJB server
• Allows use of EJB’s in your apps with little
configuration
• Why use it?
– Can be combined to work with Tomcat
– A web app in Tomcat will become an OpenEJB
client in a fully J2EE compliant way
Server-Container Contract
• Defines responsibilities between app server
and OpenEJB container
• Container manages EJBs at runtime
according. Container provides transaction,
authorization, and connector support for
beans servicing requests from the server.
The Major Steps
•
•
•
•
Install OpenEJB
Deploy an EJB from OpenEJB
Configure Tomcat
Create and Deploy the Web app
Configuring Tomcat
• Tomcat is a servlet container. OpenEJB is
an EJB container.
• Open EJB creates a runtime environment to
run EJBs and let other access them by
JNDI.
• Tomcat allows EJB’s to be bound to names
so JSPs and servlets can access them, but
there must be a bridge...
JNDI Object Factory
• Bridge between Tomcat and OpenEJB runtime
environment
• The OpenEJB class, TomcatEJBFactory interprets
bean requests and passes them to OpenEJB
• OpenEJB processes this and responds back
• Installation of the factory also requires some
classes be available for Tomcat, a simple web app
provided with OpenEJB loads the jars into
Tomcat’s class path
Configure server.xml
• EJB name bindings appear between
<Context> of the web app using the bean
•
•
•
•
•
•
•
•
•
•
•
<Ejb name="ejb/hello"
type="Session"
home="org.acme.HelloHome"
remote="org.acme.Hello"/>
<ResourceParams name="ejb/hello">
.
.
.
.
.
</ResourceParams>
Wrap-up
• Questions?
Download