350 likes | 590 Vues
Enterprise Java Beans. Web Applications. Web Tier or Presentation Tier JSP, servlet, HTML Views Business Tier Controllers Business logic Integration Tier Model. Presentation Tier. Business Tier. Integration Tier. Business Tier. Controller (MVC) Business Logic Business Methods
E N D
Web Applications • Web Tier or Presentation Tier • JSP, servlet, HTML • Views • Business Tier • Controllers • Business logic • Integration Tier • Model Presentation Tier Business Tier Integration Tier
Business Tier • Controller (MVC) • Business Logic • Business Methods • Data Transformations
What didn’t we address? • Scalability • How do we scale servlets & beans, etc? • Distributed resources • How do we access? • Component Reuseability
Enterprise Java Beans • Not Java beans! • Server-side component that encapsulates the business logic of an application. • i.e. orderProduct, transfer, deposit • Can be accessed remotely • Location transparent • Run inside a Container
EJB Container • Loads java objects • Provides for: • Remote access • Security • Resource pooling • Persistence • Concurrency • Transaction control Client container Interceptor bean bean bean bean
Why use EJBs? • Simplify the development of large, distributed applications • Container provides many services • Beans contain application logic • Separated from presentation • Particularly important for small devices • EJBs are portable • Use for new apps easily
EJB Types • Business Tier • Session • Stateless • Stateful • Message-Driven • Integration Tier • Entity
Session Beans • Represent a single client inside the application server • Clients access the application by invoking a session bean’s methods • The session bean performs the work • Shields client from complexity by executing business tasks inside the application server
Session Beans • Similar to an interactive session • Not shared - only one client • Not persistent • When the client terminates its connection, • The session bean appears to terminate • And is no longer associated with the client
Stateful Session Beans • State consists of the values of instance variables • Often called the conversational state • State is retained for the duration of the session • Disappears when client terminates connection
Stateful Session Beans • Stateful session beans are appropriate if: • A bean needs to be associated with a particular client through the life of the connection • The bean needs to hold information between method invocations • The bean manages work-flow of several enterprise beans • The bean mediates between the client and other components of the application
Stateless Session Beans • Does not maintain conversational state • When method is finished, state is not retained • All instances of stateless beans are equivalent • Pooled • Can support multiple clients • Can be used to implement a web service
Stateless Session Beans • Choose session beans if: • No direct association between a client and a specific bean • The bean performs a self-contained and generic task • All the information the bean needs can be passed as arguments to the method • Example: • Transfer(amount, account1, account2) • MailConfirmation(ordernumber, emailaddress)
Message-Driven Beans • Responds to and processes messages • Normally acts as a JMS listener • Sent by any Java EE component • Can also process other types of messages • Not accessed through interfaces • When the message arrives, the container calls the bean’s onMessage method.
Message-Driven Beans • Resembles a stateless session bean • Instances retain no data or conversational state • All instances are equivalent. • Container can assign a message to any instance • Container can pool instances • A single bean can process messages from multiple clients • However, message-driven beans are asynchronous
Entity Beans • A lightweight persistence domain object • Represents a table in a relational database • Each instance represents a row in the table • Persistent state is represented through persistent fields or properties • Object/relational mappings • Plain Old Java Object (POJO) with annotations
Entity Beans • Managed by an EntityManager • The EntityManager API creates and removes persistent entity instances, finds entities by the entity's primary key, and allows queries to be run on entities. • EntityManagers may be container controlled or application controlled
Questions to Ponder... • Entity bean, stateful session bean, stateless session bean? • object which requires access by multiple clients over its lifetime • object whose work accepts and returns all information in the call • object that must exist after server crash • object that must exist between method invocations • object that encapsulates a set of client actions to multiple beans
Example Session BeanRemote Interface package com.sun.tutorial.javaee.ejb; import java.math.BigDecimal; import javax.ejb.Remote; @Remote() public interface Converter { public BigDecimal dollarToYen(BigDecimal dollars); public BigDecimal yenToEuro(BigDecimal yen); }
Example Session BeanImplementation package com.sun.tutorial.javaee.ejb; import java.math.BigDecimal; import javax.ejb.*; @Stateless() public class ConverterBean implements Converter { private BigDecimal yenRate = new BigDecimal("115.3100"); private BigDecimal euroRate = new BigDecimal("0.0071"); public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2, BigDecimal.ROUND_UP); } public BigDecimal yenToEuro(BigDecimal yen) { BigDecimal result = yen.multiply(euroRate); return result.setScale(2, BigDecimal.ROUND_UP); } }
package com.sun.tutorial.javaee.ejb; import java.math.BigDecimal; import javax.ejb.EJB; public class ConverterClient { @EJB private static Converter converter; public ConverterClient(String[] args) {} public static void main(String[] args) { ConverterClient client = new ConverterClient(args); client.doConversion(); } public void doConversion() { try { BigDecimal param = new BigDecimal("100.00"); BigDecimal yenAmount = converter.dollarToYen(param); System.out.println("$" + param + " is " + yenAmount + " Yen."); BigDecimal euroAmount = converter.yenToEuro(yenAmount); System.out.println(yenAmount + " Yen is " + euroAmount + " Euro."); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } }
The Session Bean Interface • A plain Java interface that defines all the business methods of the bean • The interface is assumed @Local unless defined as @Remote • @Remote interface methods must have arguments and return types that are valid RMI types
package com.sun.tutorial.javaee.ejb; import java.util.List;import javax.ejb.Remote; @Remote public interface Cart { public void initialize(String person) throws BookException; public void initialize(String person, String id) throws BookException; public void addBook(String title); public void removeBook(String title) throws BookException; public List<String> getContents(); public void remove(); }
Session Bean Implementation • Must implement the interface • Must be annotated @Stateful or @Stateless • @Stateful session beans may also: • Implement lifecycle callback methods @PostConstruct, @PreDestroy, @PostActivate, @PrePassivate • Implement any optional @Remove methods
package com.sun.tutorial.javaee.ejb; import java.util.ArrayList; import java.util.List; import javax.ejb.Remove; import javax.ejb.Stateful; @Stateful public class CartBean implements Cart { String customerName; String customerId; List<String> contents; public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new ArrayList<String>(); }
…… public List<String> getContents() { return contents; } @Remove public void remove() { contents = null; } }
Lifecycle Callback Methods • Must be public, return void, and have no parameters • @PostConstruct methods • invoked by the container on newly constructed bean instances after all dependency injection has completed and before the first business method is invoked on the enterprise bean. • @PreDestroy methods • invoked after any method annotated @Remove has completed, and before the container removes the enterprise bean instance.
Lifecycle Callback Methods • @PrePassivate methods • invoked by the container before the container passivates the enterprise bean, meaning the container temporarily removes the bean fom the environment and saves it to secondary storage. • @PostActivate methods • invoked by the container after the container moves the bean from secondary storage to active status.
Business Methods • The signature of a business method must conform to these rules: • The method name must not begin with ejb • The access control modifier must be public. • If the bean allows remote access, the arguments and return types must be legal RMI types. • If the bean is a web service endpoint, the arguments and return types for the methods annotated @WebMethod must be legal types for JAX-WS. • The modifier must not be static or final. • In case of system-level errors, throw javax.ejb.EJBException
Building & Packaging • Enterprise Java Beans reside in jar files