Upload
doanthuan
View
219
Download
2
Embed Size (px)
Citation preview
1
Page 1, 5-Nov-03Component Technologies
EJB
Enterprise Java BeansEnterprise Java Beans
Mikael Åkerholm
Page 2, 5-Nov-03Component Technologies
EJB
Lecture Lecture StuctureStucture
Introduction1. Java2. JavaBeans3. J2EE
J2EE1. EJB2. Java Serverlets, JSP, and clients3. Packaging and Deployment
Summary, Questions
2
Page 3, 5-Nov-03Component Technologies
EJB
ReferencesReferences
Literature:Enterprise JavaBeans, R.M. Haefel, 3rd O’Reilly 2001
The Source for Java Technology, good, up to date, tutorials, specifications, and reference implementationshttp://java.sun.com/
Page 4, 5-Nov-03Component Technologies
EJB
JavaJava
The current main release is the Java 2 platform, it is modular and include three parts:
J2SE, Java 2 Platform, Standard Edition provides the essential compiler, tools, runtimes, and APIs for writing, deploying, and running applets and applications
J2EE, Java 2 Platform, Enterprise Edition component based model, simplifies enterprise development and deployment; manages the infrastructure and supports the web services to enable development business applications
J2ME, Java 2 Platform, Micro Editiona highly optimized Java runtime environment, specifically addresses the vast consumer space (embedded systems), from smart cards to more PC like applications
3
Page 5, 5-Nov-03Component Technologies
EJB
JavaBeansJavaBeans
A desktop component model for Java, included among the J2SE technologies
A Java API and a Specification
Software reuse for Software Development
Object-Oriented
Focus on lightweight components for small-scale CBD
Page 6, 5-Nov-03Component Technologies
EJB
JavaBeansJavaBeans
Use standard naming conventionsHave public interfacesPackaged in JAR filesInterface composed of:
Properties:Simple, Boolean or IndexedCould be Bound or Constrained
Events:signaled by changing propertiessignaled for custom state changes
Methods:default is any public methodBuilt via BeanInfo class or Reflection API
4
Page 7, 5-Nov-03Component Technologies
EJB
Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)
For enterprise applications (distributed business applications)
DemandsAvailabilitySecurityReliabilityScalability
From the early 90sShift from 2-tier, client-server application models to more flexible 3-tier (and n-tier) application modelsThe new models separated business logic from system services and the user interface
Page 8, 5-Nov-03Component Technologies
EJB
Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)
DatabaseDatabase
Tier Boundary
Businesslogic
Businesslogic
Databasedriver
Databasedriver
Businesslogic
Businesslogic
PresentationPresentation
Data tier
Business tier
Tier Boundary
Presentation tier
5
Page 9, 5-Nov-03Component Technologies
EJB
Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)
Page 10, 5-Nov-03Component Technologies
EJB
Java 2 Enterprise Edition (J2EE)Java 2 Enterprise Edition (J2EE)
J2EE Application Programming ModelApplications on the clientJava Server Pages (JSP), web components on the server, extension of Serverlets; in the end these are concerned with clients EJB, business components on the server side
6
Page 11, 5-Nov-03Component Technologies
EJB
Enterprise Enterprise JavaBeanJavaBean (EJB)(EJB)
Java’s component model for distributed enterprise applications, released 1998EJB technology defines a model for the development of reusable Java server componentsDef:
”Enterprise Java Beans is a standard server-side component for computer transaction monitors.”Applications written using EJB are:
ScalableTransactionalMulti-User secure
Page 12, 5-Nov-03Component Technologies
EJB
EJB != JBEJB != JB
Once and for allJB
Desktop ComponentsEJB
Enterprise Distributed ComponentsCould of course be implemented using JavaBeans
7
Page 13, 5-Nov-03Component Technologies
EJB
J2EEJ2EE
Page 14, 5-Nov-03Component Technologies
EJB
ContentsContents
1. EJB ComponentsGeneralInterfaces and classesArchitechtureDifferent typesTransactions
2. Java Serverlets, JSP and clientsBrief
3. Packaging and DeploymentBrief
8
Page 15, 5-Nov-03Component Technologies
EJB
What is an Enterprise What is an Enterprise JavaBeanJavaBean??
”A server-side component that encapsulates the business logic of an application”
Page 16, 5-Nov-03Component Technologies
EJB
When to use Enterprise JavaBeansWhen to use Enterprise JavaBeans
If any of these requirements hold for your application:
The application must be scalable and distributable
Transactions are required to ensure data integrity
The application will have a variety of clients
9
Page 17, 5-Nov-03Component Technologies
EJB
Enterprise JavaBeansEnterprise JavaBeans
Entity Beans
Persistent
Primary key
Session Beans
Receive their state from the client
Live as long as the client need them
Message-Driven Beans (EJB 2.0)
Asynchronously
Only a bean class – no interfaces
Page 18, 5-Nov-03Component Technologies
EJB
Classes and InterfacesClasses and Interfaces
Remote Interface
Specifies the beans business methods
Home Interface
Defines the beans life cycle methods
Bean Class
Implements the beans business methods
Primary Key
Provides a pointer into the database
10
Page 19, 5-Nov-03Component Technologies
EJB
A Bean’s interfacesA Bean’s interfaces
Remote InterfaceBusiness methods to do the beans workImplemented by the “shadowdy” Bean Object
Remote Home InterfaceDefines the beans life cycle methodsImplemented by EJB Home
Local Interface (EJB 2.0)Business methods used by other beans in the same container
Local Home Interface (EJB 2.0)Life-cycle methods used by other beans in the same container
Page 20, 5-Nov-03Component Technologies
EJB
A Bean’s classesA Bean’s classes
The Bean ClassImplement the business methodsDo not implement Remote (or local) and (local) Home InterfacesBeans exist in the middle of client software and data sourcesClients never interact directly with the bean class, uses methods of the Remote and Home Interface, interacting with automatically generated stubs
11
Page 21, 5-Nov-03Component Technologies
EJB
EJB ArchitectureEJB Architecture
HomeObjectHomeObject
EJB Server
Bean ClassBean Class
EJB Container
EJB Client
EJBObjectEJB
Object
Home InterfaceHome Interface
Remote InterfaceRemote Interface(or Local Interface)(or Local Interface)
HomeStub
HomeStub
Object Stub
Object Stub
Page 22, 5-Nov-03Component Technologies
EJB
When to use Entity BeansWhen to use Entity Beans
The bean represents a business entity, not a procedure
To provide a safe and consistent interface to a set of shared data
12
Page 23, 5-Nov-03Component Technologies
EJB
Entity BeansEntity Beans
Represents a business object in a persistent storage mechanism
Can be shared by multiple clients
Two types of persistence:
Container-managed
Bean-managed
Page 24, 5-Nov-03Component Technologies
EJB
ContainerContainer--managed persistencemanaged persistence
They are the simplest to develop
The bean’s code contain no database access calls
13
Page 25, 5-Nov-03Component Technologies
EJB
BeanBean--managed persistencemanaged persistence
Explicitly write persistence logic
More flexibility in how state is managed between the bean instance and the database
Used when deployment tools are inadequate
Page 26, 5-Nov-03Component Technologies
EJB
Life CycleLife Cycle
14
Page 27, 5-Nov-03Component Technologies
EJB
When to use Session BeansWhen to use Session Beans
Only one client has access to the beans instance
Non persistent and existing only for a short period of time
Page 28, 5-Nov-03Component Technologies
EJB
Session BeansSession Beans
Useful for describing interactions
Does not represent shared data in the database, but can access shared data
Two types:
Stateless
Stateful
15
Page 29, 5-Nov-03Component Technologies
EJB
Stateless Session BeansStateless Session Beans
Supports multiple clients
Relatively easy to develop and very efficient
Require few server resources
Stateless session beans are appropriate if:
The bean's state has no data for a specific client
A generic task is performed in a single method invocation
The bean fetches a set of read-only data
Page 30, 5-Nov-03Component Technologies
EJB
Life CycleLife Cycle
16
Page 31, 5-Nov-03Component Technologies
EJB
StatefulStateful Session BeansSession Beans
Dedicated to one client for the life of the bean instance
Instance variables represent the state of a unique client-bean session
Stateful session beans are appropriate if:
The bean needs to hold information about the client across method invocations
The bean mediates between the client and the other components of the application
Page 32, 5-Nov-03Component Technologies
EJB
Life CycleLife Cycle
17
Page 33, 5-Nov-03Component Technologies
EJB
When to use MessageWhen to use Message--Driven BeansDriven Beans
To receive messages asynchronously
When consuming JMS messages
Page 34, 5-Nov-03Component Technologies
EJB
MessageMessage--Driven BeansDriven Beans
Has only a bean class
Can consume and process messages concurrently
Acts as a JMS message listener
Deliver messages to a virtual channel
Currently process only JMS messages
18
Page 35, 5-Nov-03Component Technologies
EJB
Life CycleLife Cycle
Page 36, 5-Nov-03Component Technologies
EJB
Calling an EJBCalling an EJB
HomeObjectHomeObject
EJB Server
Bean ClassBean Class
EJB Container
EJBObjectEJB
Object
4 Create EJB Object
7 Wraps the call to the Bean Class
EJB Client
1 Ask forHome object
2 Returnreferencehome stub
JNDI
3 Ask for EJB Object
5 Return Obj stub
6 Invoke a method
19
Page 37, 5-Nov-03Component Technologies
EJB
Transactions with Transactions with EJBsEJBs
Managed automatically
No use of APIDefined at deployment
Possible to explicitly manage transactions but not recommended
Page 38, 5-Nov-03Component Technologies
EJB
A Transaction A Transaction
Transactions is the execution of a unit-of-work that accesses on or more resources, usually databasesA unit-of-work is a set of activities that relate to each other and must be completed together
The objective with transactions is to execute an unit-of work that results in a reliable exchangeTransactions are often complex and usually involve manipulation of dataTransactions must work perfectly every time or not be executed at all
20
Page 39, 5-Nov-03Component Technologies
EJB
AcidAcid--propertiesproperties
AtomicA transaction must execute completely or not at all
ConsistentA transaction always leads to a correct transformation of the system state by preserving the state invariance
IsolatedThe data a transaction access cannot be affected by any other parts of the system until the transaction is completed
DurableAll the data changes made during the course of transaction must be written to a physical storage before the transactions is physically completed
Page 40, 5-Nov-03Component Technologies
EJB
Transaction ManagementTransaction Management
Declarative transaction managementThe transactional behavior controls by using transactions attribute in the deployment descriptorOne of the primary advantages of EJBReduce the complexity for the developersMakes it easier to create robust transaction applications
Explicit transaction managementDifficult to useWill not be covered in this talk
21
Page 41, 5-Nov-03Component Technologies
EJB
Transactions AttributeTransactions AttributeYou can set the runtime transaction attribute as a XML-attribute in the deployment descriptor by hand, but we will use a deployment wizardIt is more efficient and easier to use transaction attributes than to control transactions explicitlyIt is possible to set a transaction attribute for the entire bean or to set different transactions attribute for individual methodsThere exist six transaction attributes in EJB 2.0:
NotSupportedSupportsRequiredRequiresNewMandatoryNever
Page 42, 5-Nov-03Component Technologies
EJB
The Different Transactions AttributesThe Different Transactions Attributes
NotSupportedInvoking a method on a bean with this transaction attribute suspends the transactions until the method is completed
SupportsMeans that the bean method will be included in the transactions scope if it is invoked within a transaction
RequiredMeans that the bean method must be invoked within the scope of a transaction
22
Page 43, 5-Nov-03Component Technologies
EJB
The Different Attributes, Cont.The Different Attributes, Cont.
RequiresNewMeans that a new transactions always starts
MandatoryMeans that the bean method must always be made part of the transaction scope of the calling client
NeverMeans that the bean method must never be invoked within the scope of a transaction
Page 44, 5-Nov-03Component Technologies
EJB
Java Java ServerletsServerlets, JSP and clients, JSP and clients
23
Page 45, 5-Nov-03Component Technologies
EJB
ServerletsServerlets
A serverlet is a server side component, which is deployed in the same fashion as a EJBUsed to dynamically create html pages, for clients
Since it is server side, it extends the reach for clients to backend components (e.g., EJBs) in the server
A servelet is assigned to handle an access for a specifichtml page
When the specific page is requsted by a browser, a method in the servelet is envoked which posts the html page back
When a client looks at the html code posted from the server, it looks just like a static html page
Page 46, 5-Nov-03Component Technologies
EJB
JavaServerJavaServer Pages, JSPPages, JSP
An extension of serverlets, simplifies the creation of dynamic html Simply lets the developer incorporate real java code intoa html page when desired (as a scripting language)Is actually compiled to servelets
24
Page 47, 5-Nov-03Component Technologies
EJB
ClientsClients
Web clients with serverlets or JSP, JSP possibly morepowerfulCan also create application clients
An client side component, that access EJBsEasy and straightforward to create, deploted in the same fashion as EJBs
Page 48, 5-Nov-03Component Technologies
EJB
Packaging and DeploymentPackaging and Deployment
25
Page 49, 5-Nov-03Component Technologies
EJB
Deployment and Deploy ToolsDeployment and Deploy Tools
PackagingCreate JAR files
A compressed platform-independent fileBean and Beans interface and help classes
Create deployment descriptorsXML files specifyingAccess controlBean referencesExternal Resource referencesTransactional attributes
DeploymentDeploy the application on a server
Page 50, 5-Nov-03Component Technologies
EJB
PackagingPackaging and and DeploymentDeployment
Can be done by handGives full controlTime consuming
Graphical deplytool with wizards included in the reference implementation
Easy, fast
26
Page 51, 5-Nov-03Component Technologies
EJB
SummarySummary
JB != EJBEJBs Typically used for 3 or more tiers bussinessapplicationsEJBs, server side components, with remote and homeinterfaces; packaged in JAR files with deploymentdescriptors
Session, Entity, MessageClients, can be applications or web pages throughservelets or JSP
Page 52, 5-Nov-03Component Technologies
EJB
ExampleExampleEntity Bean PersonEntity Bean Person
“Let’s look how to build a bean”
27
Page 53, 5-Nov-03Component Technologies
EJB
The Remote InterfaceThe Remote Interface
/**/**Remote InterfaceRemote InterfaceBusiness methods for Person beansBusiness methods for Person beans*/*/
import import javax.ejb.Exceptionjavax.ejb.Exception;;
public interface Person extends public interface Person extends javax.ejb.EJBObjectjavax.ejb.EJBObject {{String String getNamegetName() throws () throws RemoteExceptionRemoteException;;void void setName(StringsetName(String n) throws n) throws RemoteExceptionRemoteException;;
}}
Page 54, 5-Nov-03Component Technologies
EJB
The Home InterfaceThe Home Interface
/**/**Home InterfaceHome InterfaceLife cycle method for Person beansLife cycle method for Person beans*/*/
import import java.rmi.RemoteExceptionjava.rmi.RemoteException;;import import javax.ejb.CreateExceptionjavax.ejb.CreateException;;import import javax.ejb.FinderExceptionjavax.ejb.FinderException;;
public interface public interface PersonHomePersonHome extends extends javax.ejb.EJBHomejavax.ejb.EJBHome {{
//responsible for //responsible for initalizinginitalizing an instance of the beanan instance of the beanpublic Person public Person create(intcreate(int id)id)
throws throws CreateExceptionCreateException, , RemoteExceptionRemoteException;;
//look up a bean in a DB//look up a bean in a DBpublic public findByPK(PersonPKfindByPK(PersonPK pkpk))
throws throws FinderExceptionFinderException, , RemoteExceptionRemoteException;;}}
28
Page 55, 5-Nov-03Component Technologies
EJB
The Bean ClassThe Bean Class/**/**Bean ClassBean ClassImplements the business methods for Person componentImplements the business methods for Person componentPerson Bean is a Entity BeanPerson Bean is a Entity Bean*/*/public class public class PersonBeanPersonBean implements implements javax.ejb.EntityBeanjavax.ejb.EntityBean {{
private private intint id;id;private String name;private String name;
//business methods//business methodspublic Sting public Sting getNamegetName() {() {
return name;return name;}}
public void public void setName(StringsetName(String n) {n) {name=n;name=n;
}}
// continue next slide…// continue next slide…
Page 56, 5-Nov-03Component Technologies
EJB
// … and the bean class continues// … and the bean class continues////ejb.entityejb.entity methodsmethods
public public PersonPKPersonPK ejbCreate(intejbCreate(int i) {i) {id=i;id=i;return null;return null;
}}
public void public void ejbPostCreate(intejbPostCreate(int i) {/*+*/}i) {/*+*/}public void public void ejbSetEntityContext(EntityContextejbSetEntityContext(EntityContext ctxctx) {}) {}public void public void ejbUnsetEntityContextejbUnsetEntityContext() {/*+*/}() {/*+*/}public void public void ejbActivateejbActivate() {}() {}public void public void ejbPassivateejbPassivate() {}() {}public void public void ejbLoadejbLoad() {/*+*/}() {/*+*/}public void public void ejbStoreejbStore() {/*+*/}() {/*+*/}public void public void ejbRemoveejbRemove() {}() {}
// + note: session beans do not have these methods// + note: session beans do not have these methods}}
29
Page 57, 5-Nov-03Component Technologies
EJB
ExampleExampleSimple JSP pageSimple JSP page
“How to build a web client”
Page 58, 5-Nov-03Component Technologies
EJB
<%<%---- A A jspjsp filefile that that useuse a session a session beanbean ----%>%>
<%@ page <%@ page import="Converter,ConverterHome,javax.ejbimport="Converter,ConverterHome,javax.ejb.*, .*, java.mathjava.math.*, .*, javax.namingjavax.naming.*, .*, javax.rmi.PortableRemoteObjectjavax.rmi.PortableRemoteObject, , java.rmi.RemoteExceptionjava.rmi.RemoteException" %>" %>
<%!<%!private private ConverterConverter converterconverter = = nullnull;;
<%<%---- The The initinit methodmethod, JNDNI , JNDNI lookuplookup ----%>%>public public voidvoid jspInitjspInit() { () {
try {try {InitialContextInitialContext icic = new = new InitialContextInitialContext();();Object Object objRefobjRef = = ic.lookup("java:compic.lookup("java:comp//envenv//ejbejb//TheConverterTheConverter");");ConverterHomeConverterHome homehome = =
((ConverterHome)PortableRemoteObject.narrow(objRef,ConverterHome.cConverterHome)PortableRemoteObject.narrow(objRef,ConverterHome.classlass););
converterconverter = = home.createhome.create();();} } catchcatch ((ExceptionException ex) {ex) {
System.out.println("Couldn'tSystem.out.println("Couldn't createcreate converterconverter beanbean."+ ."+ ex.getMessageex.getMessage());());
}}
30
Page 59, 5-Nov-03Component Technologies
EJB
public public voidvoid jspDestroyjspDestroy() { () { converterconverter = = nullnull;;
}}%>%><html><html><form <form method="getmethod="get">"><input <input type="texttype="text" " name="amountname="amount" size="25">" size="25"><input <input type="submittype="submit" " value="Submitvalue="Submit"> </form>"> </form><%<%
StringString amountamount = = request.getParameter("amountrequest.getParameter("amount");");ifif ( ( amountamount != != nullnull && && amount.lengthamount.length() > 0 ) {() > 0 ) {
BigDecimalBigDecimal d = new d = new BigDecimalBigDecimal ((amountamount););%>%>
<%= <%= amountamount %> Kronor are <%= %> Kronor are <%= converter.yenToEuro(dconverter.yenToEuro(d) %> ) %> Euro.Euro.
<%<%}}
%>%></</bodybody>></html></html>
Page 60, 5-Nov-03Component Technologies
EJB
ExampleExampleA deployment descriptorA deployment descriptor
“Good to understand, when time allows!”
31
Page 61, 5-Nov-03Component Technologies
EJB
XML Document HeaderXML Document Header
XML documents start with two general information tags:
1. Specifies the XML version the file use<?xml version=”1.0”?>
2. Specifies the DTD that defines the XML fileProvides the URL to the DTD, you can download it and validate the XML file<!DOCTYPE ejb-jar PUBLIC ”-//Sun Microsystems, Inc.//DTD Enterprise JavaBean 1.1//EN” ”http://java.sun.com/j2ee/dtds/ejb-jar.dtd”>
Page 62, 5-Nov-03Component Technologies
EJB
XML Descriptor’s BodyXML Descriptor’s Body
The Body start with a root element defined by the DTD.The root element describing:
Bean/ Beans <enterprise-beans>Entity or Session BeansPrimary KeyEnvironment EntriesReference to other BeansReference to External Resources (such as a Database)Security Roles
Bean/Beans Assembly <assembly-description>Transactional attributesSecurity roles & Method permissions
32
Page 63, 5-Nov-03Component Technologies
EJB
XML Body exampleXML Body example
<ejb<ejb--jar>jar><description>a body example</description><description>a body example</description><enterprise<enterprise--bean>bean>
<session><session>-- -- --
</session></session><entity><entity>
-- -- --</entity></entity>
-- -- --</enterprise</enterprise--bean>bean>
<assembly<assembly--descriptor> descriptor> -- -- --
</assembly</assembly--descriptor> descriptor> </ejb</ejb--jar>jar>
Page 64, 5-Nov-03Component Technologies
EJB
<entity><entity><description> a Bean example </description><description> a Bean example </description><ejb<ejb--name>name>PlayerBeanPlayerBean</ejb</ejb--name>name><home><home>com.chess.player.PlayerHomecom.chess.player.PlayerHome</home></home><remote>com.chess.player.Player</remote><remote>com.chess.player.Player</remote><ejb<ejb--class> class> com.chess.player.PlayerBeancom.chess.player.PlayerBean</ejb</ejb--class>class><persistence<persistence--type>Container</persistencetype>Container</persistence--type>type><prim<prim--keykey--class>java.lang.Integer</primclass>java.lang.Integer</prim--keykey--class>class><<primkeyprimkey--field>id</field>id</primkeyprimkey--field>field><reentrant>False</reentrant><reentrant>False</reentrant><<cmpcmp--field><fieldfield><field--name>id</fieldname>id</field--name></name></cmpcmp--field>field>
-- -- --<<cmpcmp--field><fieldfield><field--name>name</fieldname>name</field--name></name></cmpcmp--field>field>
</entity></entity>
XML Bean exampleXML Bean example
33
Page 65, 5-Nov-03Component Technologies
EJB
<ejb-jar><enterprise-beans>...</enterprise-beans>…<assembly-descriptor>
<container-transaction> … </container-transaction> <security-role>
<description>allows to read/write</description><role-name>everyone</role-name>
</security-role><method-permission>
<role-name>everyone</role-name><method>
<ejb-name>myBean</ejb-name><method-name>*</method-name>
</method></method-permission>
</assembly-descriptor>
XML XML Security Roles and Method permissionsSecurity Roles and Method permissions