Upload
niimalost
View
218
Download
0
Embed Size (px)
Citation preview
8/2/2019 J2EE and Ejb
1/58
J2EE and Enterprise Java Beans
Ajay Bajaj
Kunal Mehta
Arun MarioliDhairya Shah
8/2/2019 J2EE and Ejb
2/58
Distributed Multi-tiered Applications
The J2EE platform uses a multi-tiered distributedapplication model for both enterprise applications
Application logic is divided into components
according to function, and the various applicationcomponents that make up a J2EE application areinstalled on different machines depending on the tierin the multi-tiered J2EE environment to which theapplication component belongs
8/2/2019 J2EE and Ejb
3/58
J2EE Architecture
J2EE multi-tieredapplications are generallyconsidered to be three-tiered
applications because theyare distributed over threedifferent locations
client machines
the J2EE server machine
the database or legacymachines at the back end
8/2/2019 J2EE and Ejb
4/58
J2EE Architecture
Three-tiered applicationsthat run in this way extendthe standard two-tiered client
and server model by placinga multithreaded applicationserver between the clientapplication and back-endstorage
8/2/2019 J2EE and Ejb
5/58
J2EE Containers
The application server maintains control andprovides services through an interface or
framework known as a container There are five defined container types in the
J2EE specification
8/2/2019 J2EE and Ejb
6/58
Server J2EE Containers
Three of these are server-side containers: The server itself, which provides the J2EE runtime
environment and the other two containers
An EJB container to manage EJB components A Web container to manage servlets and JSP pages
8/2/2019 J2EE and Ejb
7/58
Client J2EE Containers
The other two container types are client-side: An application container for stand-alone GUIs, console
An applet container, meaning a browser, usually with
the Java Plug-in
8/2/2019 J2EE and Ejb
8/58
J2EE Components
As said earlier, J2EE applications are madeup of components
A J2EE componentis a self-containedfunctional software unit that is assembled intoa J2EE application with its related classesand files and that communicates with other
components
8/2/2019 J2EE and Ejb
9/58
Components
Client components run on the client machine,which correlate to the client containers
Web components -servlets and JSP pages EJB Components
8/2/2019 J2EE and Ejb
10/58
Packaging Applications andComponents
Under J2EE, applications and componentsreside in Java Archive (JAR) files
These JARs are named with differentextensions to denote their purpose, and theterminology is important
8/2/2019 J2EE and Ejb
11/58
Various File types
Enterprise Archive (EAR) files represent theapplication, and contain all other server-sidecomponent archives that comprise theapplication
Client interface files and EJB componentsreside in JAR files
Web components reside in Web Archive(WAR) files
8/2/2019 J2EE and Ejb
12/58
Deployment Descriptors
Deployment descriptors are included in the JARs, alongwith component-related resources
Deployment descriptors are XML documents that describeconfiguration and other deployment settings (remember
that the J2EE application server controls many functionalaspects of the services it provides)
The statements in the deployment descriptor aredeclarative instructions to the J2EE container; for example,transactional settings are defined in the deployment
descriptor and implemented by the J2EE container
8/2/2019 J2EE and Ejb
13/58
Deployment Descriptors
Most J2EE Web Services vendors provide a GUI toolfor generating deployment descriptors andperforming deployment because creating manual
entries is tedious and error prone
The deployment descriptor for an EJB componentmust be named ejb-jar.xml, and it resides in theMETA-INF directory inside the EJB JAR file
8/2/2019 J2EE and Ejb
14/58
EJB Components
EJB components are server-side, modular, andreusable, comprising specific units of functionality
They are similar to the Java classes we create every
day, but are subject to special restrictions and mustprovide specific interfaces for container and clientuse and access
We should consider using EJB components forapplications that require scalability, transactionalprocessing, or availability to multiple client types
8/2/2019 J2EE and Ejb
15/58
EJB Components- Major Types
Session beans These may be either statefulor statelessand are primarily
used to encapsulate business logic, carry out tasks on behalfof a client, and act as controllers or managers for other beans
Entity beans Entity beans represent persistent objects or business
concepts that exist beyond a specific application's lifetime;they are typically stored in a relational database
8/2/2019 J2EE and Ejb
16/58
The homeand componentinterface
A bean's home interface specifies methods that allow theclient to create, remove, and find objects of the same type
The home interface provides bean management and lifecycle methods
EJB functionality is obtained through the bean'scomponent interface, which defines the business methodsvisible to, and callable by, the client
The developer writes the component interface, and the
container creates the implementation for client interaction
8/2/2019 J2EE and Ejb
17/58
Overview
Enterprise JavaBeans is a specification for creatingserver-side secure, scalable, transactional, multi-usersecure enterprise-level applications.
These server-side components, called enterprisebeans, are distributed objects that are hosted inEnterprise Java Bean containers and provide remoteservices for clients distributed throughout the
network.
8/2/2019 J2EE and Ejb
18/58
Java Beans vs. EJB
Can be either visible non-visible.
Local Invocation Synchronous Invocation
Decidedly non-visible remoteobjects
Remote and Local Invocation Synchronous and
Asynchronous Invocation Object Pooling Transparent Persistence Supports Transactions Support Relationships
between entity EJBs J2EE Security Features
8/2/2019 J2EE and Ejb
19/58
Advantages of EJB
Simplifies the development of middlewarecomponents that are secure, transactional,scalable & portable.
Simplifies the process to focus mainly onbusiness logic rather than applicationdevelopment.
Overall increase in developer productivity
Reduces the time to market for mission criticalapplications
8/2/2019 J2EE and Ejb
20/58
Purpose of EJBs
SESSION Beans (verbs of the system):
Model task or workflow
Faade for Entity beans
Maintain conversational state with clients
ENTITY Beans (nouns of the system):
Object/Relational (O/R) mapping
Transparent and implicit persistence with transaction support
Message Driven Beans:
Asynchronous communication with MOM
Conduit for non-J2EE resources to access Session and EntityBeans via JCA Resource adapters.
8/2/2019 J2EE and Ejb
21/58
EJB serveraka Enterprise Java Server (EJS)
EJS are analogous to the CORBA ORB. Part of an application server that hosts EJB containers EJBs do not interact directly with the EJB server EJB specification outlines eight services that must be provided by an
EJB server: Naming Transaction Security Persistence Concurrency
Life cycle Messaging Timer
8/2/2019 J2EE and Ejb
22/58
Three Tier Architecture UsingEJBs
MessageBroker
EJB Container
EntityEJBwCMP
SessionEJB
WEB Container
ServletLocal
Interface
Remote
Interface
EIS RDBMS
MsgDrvEJB
JDBC
JCAResouceAdapter
JMS
EIS other
Presentation Business Data
Queue/TopicJMS
EntityEJBwBMP
EntityEJBwCMP = Entity Bean with Container Managed PersistenceEntityEJBwBMP = Entity Bean with Bean Managed PersistenceMsgDrvEJB = Message Driven EJB
EIS other
8/2/2019 J2EE and Ejb
23/58
EJB Container
Functions as a runtime environment for EJBcomponents beans
Containers are transparent to the client in that thereis no client API to manipulate the container
Container provides EJB instance life cyclemanagement and EJB instance identification.
Manages the connections to the enterpriseinformation systems (EISs)
8/2/2019 J2EE and Ejb
24/58
EJB Container(contd)
8/2/2019 J2EE and Ejb
25/58
EJB Client
Finds EJB container via JNDI.
Invokes methods on EJB beans.
8/2/2019 J2EE and Ejb
26/58
EJB components
8/2/2019 J2EE and Ejb
27/58
EJB Interfaces -Local and Remote
Local Interface Used for invoking EJBs within the same JVM (process) @Local annotation marks an interface local Parameters passed by reference
Remote Interface Used for invoking EJBs across JVMs (processes) @Remote annotation marks an interface remote Parameters passed by value (serialization/de- serialization)
Note: An EJB can be implement both interfaces if needed.
8/2/2019 J2EE and Ejb
28/58
Business Interface
Defines business methods
Session beans and message-driven beansrequire a business interface, optional forentity beans.
Business interface do not extend local orremote component interface unlike EJB2.x
Business Interfaces are POJIs (Plain OldJava Interfaces)
B i I f l
8/2/2019 J2EE and Ejb
29/58
Business Interface - examples
Shopping cart that maintains state
public interface ShoppingStatefulCart {
void startShopping(String customerId);
void addProduct(String productId);
float getTotal();
} Shopping cart that does not maintain state
public interface ShoppingStatelessCart {
String startShopping(String customerId); //return cartId
void addProduct(String cartId, String productId);float getTotal(String cartId);
}
S l S i EJB (SLSB)
8/2/2019 J2EE and Ejb
30/58
Stateless Session EJB (SLSB)
Does not maintain any conversational state with client Instances are pooled to service multiple clients @Stateless annotation marks a been stateless.
Lifecycle event callbacks supported for stateless sessionbeans (optional) @PostConstructoccurs before the first business method
invocation on the bean @PreDestroyoccurs at the time the bean instance is
destroyed
8/2/2019 J2EE and Ejb
31/58
Stateless Session EJBexample (1/2)
The business interface:public interface HelloSessionEJB3Interface{
public String sayHello();
}
8/2/2019 J2EE and Ejb
32/58
Stateless Session EJBexample (2/2)
The stateless bean with local interface:import javax.ejb.*;import javax.annotation.*;@Local({HelloSessionEJB3Interface.class})@Statelesspublic class HelloSessionEJB3 implements
HelloSessionEJB3Interface{public String sayHello(){
return "Hello from Stateless bean;}@PreDestroyvoid restInPeace() {
System.out.println(I am about to die now);
}}
St t f l S i EJB (SFSB)
8/2/2019 J2EE and Ejb
33/58
Stateful Session EJB (SFSB)
Maintains conversational state with client
Each instance is bound to specific client session
Support callbacks for the lifecycle events listed
on the next slide
8/2/2019 J2EE and Ejb
34/58
SFSB Lifecycle Events
@PostConstructsame as SLSB, once for each session @PreDestroysame as SLSB, once for each session @PostActivatecontainer picks a instance from pool and
assigns to a specific client session
@PrePassivatecontainer returns the instance to pool afterthe session is terminated
@Initdesignates the initialization method of a statefulsession bean
@Removecauses the container to remove the stateful session
bean, first invoking the beans PreDestroy method if any
Stateful Session EJB example
8/2/2019 J2EE and Ejb
35/58
Stateful Session EJB example(1/2)
Define remote business interface (remote can bemarked in bean class also) :
@Remotepublic interface ShoppingCart {
public void addItem(String item);public void addItem(String item);
public Collection getItems();
}
St t f l S i EJB l
8/2/2019 J2EE and Ejb
36/58
Stateful Session EJB example(2/2)
@Statefulpublic class CartBean implementsShoppingCart {private ArrayList items;@PostConstructpublic void initArray() {
items = new ArrayList();}
public void addItem(String item) {items.add(item);
}public void removeItem(String item) {
items.remove(item);}public Collection getItems() {
return items;}@Removevoid logoff() {items=null;}
}
8/2/2019 J2EE and Ejb
37/58
Entity EJB (1)
It is permanent. Standard Java objects come intoexistence when they are created in a program. When theprogram terminates, the object is lost. But an entity beanstays around until it is deleted. In practice, entity beans
need to be backed up by some kind of permanent storage,typically a database. A program can create an entity bean,then the program can be stopped and restarted. The entitybean will continue to exist. After being restarted, theprogram can again find the entity bean it was working with,
and continue using the same entity bean.
8/2/2019 J2EE and Ejb
38/58
Entity EJB (2)
It is identified by a primary key. Entity Beans musthave a primary key. The primary key is unique --each entity bean is uniquely identified by its primary
key. For example, an "employee" entity bean mayhave Social Security numbers as primary keys. Youcan only use entity beans when your objects have aunique identifier field, or when you can add such a
field. Note: Session beans do not have a primary key.
8/2/2019 J2EE and Ejb
39/58
Entity Bean Class
@Entity annotation marks a class as Enity EJB
Persistent state of an entity bean is represented bynon-public instance variables
For single-valued persistent properties, these methodsignatures are: getProperty()
void setProperty( t)
Must be a non-final concrete class
Must have public or protected no-argumentconstructor
8/2/2019 J2EE and Ejb
40/58
Entity Bean Class (cont.)
No methods of the entity bean class may be final If entity bean must be passed by value (through a
remote interface) it must implementSerializableinterface.
8/2/2019 J2EE and Ejb
41/58
Entity EJB
CMP (Container Managed Persistence) Container maintains persistence transparently using
JDBC calls
BMP (Bean Managed Persistence) Programmer provides persistence logic
Used to connect to non-JDBC data sources like LDAP,mainframe etc.
Useful for executing stored procedures that returnresult sets
8/2/2019 J2EE and Ejb
42/58
Entity EJB example (1)
@Entity // mark as Entity Beanpublic class Customer implements Serializable {
private Long id;private String name;private Collection orders = new
HashSet();@Id(generate=SEQUENCE) // primary keypublic Long getId() {return id;}public void setId(Long id) {
this.id = id;}
8/2/2019 J2EE and Ejb
43/58
Entity EJB example (2)
@OneToMany // relationship between Customerand Orders
public Collection getOrders() {return orders;}
public void setOrders(Collectionorders) {
this.orders = orders;}
}
8/2/2019 J2EE and Ejb
44/58
EntityManager
EntityManager API is used to:
create and remove persistent entity instances
to find entities by their primary key identity, and to
query over entities
EntityManager supports EJBQL and (non-portable)native SQL
8/2/2019 J2EE and Ejb
45/58
Entity Bean Life CycleEntity bean instance has four possible states: New entity bean instance has no persistent identity, and is not
yet associated with a persistence context. Managed entity bean instance is an instance with a persistent
identity that is currently associated with a persistence context. Detachedentity bean instance is an instance with a persistentidentity that is not (or no longer) associated with a persistencecontext.
Removed entity bean instance is an instance with a persistent
identity, associated with a persistence context, scheduled forremoval from the database.
Example of Use of
8/2/2019 J2EE and Ejb
46/58
Example of Use ofEntityManager API
@Stateless public class OrderEntry {
@Inject EntityManager em;
public void enterOrder(int custID, OrdernewOrder) {
Customer cust =(Customer)em.find("Customer",
custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
8/2/2019 J2EE and Ejb
47/58
Message Driven EJB example
8/2/2019 J2EE and Ejb
48/58
Message Driven EJB example
import javax.jms.Message;import javax.jms.MessageListener;import javax.ejb.MessageDriven;@MessageDrivenpublic class MessageDrivenEJBBean implements
MessageListener {
public voidonMessage(Message message) {if(message instanceof MyMessageType1)
doSomething(); // business method 1if(message instanceof MyMessageType2)
doSomethingElse(); // business method 2
}}
EJB Query Language (EJBQL)
8/2/2019 J2EE and Ejb
49/58
EJB Query Language (EJBQL)
EJBQL : RDBMS vendor independent querysyntax
Query API supports both static queries (i.e.,named queries) and dynamic queries.
Since EJB3.0, supports HAVING, GROUPBY, LEFT/RIGHT JOIN etc.
8/2/2019 J2EE and Ejb
50/58
EJBQL - examples Define named query:@NamedQuery(
name="findAllCustomersWithName",queryString="SELECT c FROM Customer c WHERE c.nameLIKE :custName"
) Use named query:@Inject public EntityManager em;//..List customers =
em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith")
.getResultList();
8/2/2019 J2EE and Ejb
51/58
EJB Security Architecture
Client Security: The Enterprise JavaBean (EJB) server automatically
performs the steps necessary to ensure that deployed
enterprise bean applications are only available toauthorized users.
One of these steps is authenticating clients thatrequest access to EJB homes, beans, and individualmethods on the beans.
8/2/2019 J2EE and Ejb
52/58
Understanding EJB Security
Two security measures that client must pass when you addsecurity to EJB systemAuthenticationand Authorization.
Authentication must be performed before any EJB method iscalled.
Authorization occurs at the beginning of each EJB methodcall.
8/2/2019 J2EE and Ejb
53/58
Authentication in EJB
Two ways to perform authentication in EJB: We can call authentication logic through Java Authentication
and Authorization Service(JAAS), a separate J2EE API.
JAAS is a portable interface that enables you to authenticateand authorize users in Java. It allows to login to the systemwithout knowing about the underlying security system beingused.
8/2/2019 J2EE and Ejb
54/58
Authorization in EJB
Two ways to perform authorization in EJB: With programmatic authorization, we can hard code security
checks into our bean code.
With declarative authorization, the container performs allauthorization checks for us.
8/2/2019 J2EE and Ejb
55/58
Deploying EJBs
EJB 3.0 annotations will replace EJB 2.0deployment descriptors in almost all cases
Values can be specified using annotations inthe bean class itself
Deployment descriptor may be usedtooverride the values from annotations
8/2/2019 J2EE and Ejb
56/58
Some EJB Servers
Company Product
IBM WebSphere BEA Systems BEA WebLogic
Sun Microsystems Sun Application Server Oracle Oracle Application Server JBoss JBoss
8/2/2019 J2EE and Ejb
57/58
References (1) SUN EJB Specifications
http://java.sun.com/products/ejb/docs.html IBM RedBooks
http://www.redbooks.ibm.com/redbooks.nsf/redbooks/
IBM WebSphere Developer Technical Journalhttp://www.ibm.com/developerworks/websphere/
Oracle Technology Networkhttp://www.oracle.com/technology/tech/java/index.html
http://java.sun.com/products/ejb/docs.htmlhttp://www.redbooks.ibm.com/redbooks.nsf/redbooks/http://www.ibm.com/developerworks/websphere/http://www.oracle.com/technology/tech/java/index.htmlhttp://www.oracle.com/technology/tech/java/index.htmlhttp://www.ibm.com/developerworks/websphere/http://www.redbooks.ibm.com/redbooks.nsf/redbooks/http://java.sun.com/products/ejb/docs.html8/2/2019 J2EE and Ejb
58/58
References (2)
Java.net http://www.java.net/
JavaWorldwww.javaworld.com/channel_content/jw-ejbs-index.shtml
TheServerSidehttp://www.theserverside.com/
Richard Monson-Haefel, Enterprise JAVABEANS
Tate, Clark, Lee, Lisnkey, BITTER EJB
Feghhi, Jalal, Web developer's guide to JavaBeans
http://www.java.net/http://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.theserverside.com/http://www.theserverside.com/http://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.javaworld.com/channel_content/jw-ejbs-index.shtmlhttp://www.java.net/