200 likes | 310 Vues
Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0. Session Beans. Enterprise Java Beans (EJB). An EJB is a component that provides reusable business logic functionality and/or a representation of a persistent business entity
E N D
Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0 Session Beans
Enterprise Java Beans (EJB) • An EJB is a component that provides reusable business logic functionality and/or a representation of a persistent business entity • An EJB Container executes an EJB on behalf of clients. • Container provides the plumbing necessary to execute the EJB including • non-business logic related functionality such as transactions, security, concurrency, remote access, etc. • life cycle functions, e.g., creating, destroying, etc. • Client uses an interface to access the Bean indirectly • A deployment descriptor describes the structure of the Bean and how to execute the Bean as part of an application
Session Beans • Session Beans are one type of EJBs • other types are Entity Beans and Message Driven Beans • A session bean executes on behalf of a single client • Focus on functionality, application logic and application state • May be transaction aware • May access shared data in an underlying DB but does not directly represent this shared data • Is relatively short-lived • Is removed when the EJB Container crashes
Stateless Session Beans • A Stateless Session Bean executes a request and returns a result without saving any client specific state information • Can use instance variables only if they are not client related (do not expect instance variables value to remain the same) • All Stateless Session Beans are equivalent • A container can choose • To serve the same instance of a Bean to multiple clients • To serve difference Bean instances to the same client at different times • A container may maintain a pool of Stateless Session Beans • No necessary relation between when a client creates the Bean and when the Container creates the Bean • Provide very high scalability
Stateful Session Beans • Maintain per client state across multiple client requests • May be “passivated” – allows a degree of pooling • The container serializes the state of a Bean non currently being used and writes it to a secondary storage • Frees JVM resources held for Bean • When a new request arrives for the Bean, it must be “activated” • State read from secondary storage and deserialized • Can only passivate a Bean if it is not in a transaction
Stateful Session Beans create passivate Does Not Exist Ready Passive remove activate start transaction commit or rollback In Transaction timeout
EJB Development Steps • Write Business Interface • Plain Java Interface exposing the EJB business methods can be local or remote • Write Bean Class • Implementation of Business Interface • Use annotations (e.g. to specify type of EJB) • Use resource injection (e.g. for persistence access) • Provide deployment descriptor (if needed) • Package and deploy on container • Usually done by a container provided tool
EJB Development StepsLocal versus Remote Interface • There are two types of Interface to EJBs • local interface – for clients running in the same Java Virtual Machine (JVM) as the EJB • remote interface – for clients running in different (JVM) than the EJB • A local interface should be used whenever possible • local interface provides a better performance (an actual reference to an instance of EJB is used) • remote interface involves RMI (creation of stub and skeleton objects, marshalling/unmarshalling messages, ...)
EJB Development Steps Interface package helloejb; import javax.ejb.Remote; /** * This is the business interface for HelloEJB enterprise bean. */ @Remote // specify as a remote interface public interface Hello { public String hello(); } The annotation for the type of interface could be omited from the interface and specified in the EJB implementation.
EJB Development Steps package helloejb; import javax.ejb.Stateless; @Stateless // for a stateless session EJB public class HelloEJBBean implements helloejb.Hello { /** Creates a new instance of HelloEJBBean */ public HelloEJBBean() { } /** Implementation of business method */ public String hello() { return "Hello from ejb !!!"; } } Stateless Session EJB Implementation
EJB Client • An EJB client can be managed by the same container as the EJB (e.g. a Servlet or another EJB) or external. • Container managed clients can use ressource injection for access (using annotation @EJB) • Non-container managed clients must use JNDI to locate the EJB.
EJB Client package servlet; import helloejb.Hello; ... public class HelloClientServlet extends HttpServlet { @EJB // EJB ressource injection private Hello hello; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<h1>EJB returns " + hello.hello()); out.println("</body>"); out.println("</html>"); out.close(); } ... } Web application client, managed by the same container
EJB Client import helloejb.Hello; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class HelloClient { public static void main(String[] args) { Context ctx; try { /** Use JNDI to lookup */ ctx = new InitialContext(); Hello helloEjb = (Hello) ctx.lookup("helloejb.Hello"); System.out.println(helloEjb.hello()); } catch (NamingException ex) { ex.printStackTrace(); } } } Stand-alone client, managed outside of container. Need to use JNDI to lookup.
Session EJBs Annotations • @Stateless declares a stateless session EJB @Stateless(name=”TR”) public class TaxRateBean implements TaxRate { } • By default, name is the same as the class name. • @Stateful declares a stateful session EJB • @Remote can be use to annotate EJB class @Stateless @Remote(TaxRate.class) public class TaxRateBean implements TaxRate { } • In that case, the interface do not have a @Remote or @Local annotation
Session EJBs Annotations • Annotations are also used for dependency injection • mechanism allowing to obtain object references on resources from the container • @Resource set up a dependency to a resource in the bean's environment @Resource SessionContext context; TaxRate tr = (TaxRate)context.lookup(TaxRate.class.getName()); • Any resource available to the application server can be referred to (javax.sql.DataSource, javax.transaction.UserTransaction, ...)
Session EJBs Annotations • @EJB can be used to inject a reference to an EJB or bind a name in the EJB environment • Injection of a EJB reference @EJB private Pricer pricer; • Binding a name in the EJB environment @EJB(name=”ejb/TaxRate”,beanInterface=TaxRate.class) @Stateless public class PricerBean implements Pricer { ... public double getFinalPrice() { InitialContext ctx = new InitialContext(); TaxRate tr = (TaxRate)context.lookup(“java:comp/env/ejb/TaxRate”); } }
Session EJBs Annotations • @PersistenceContext to inject an entity manager object or bind a name at the class level • Injection of an entity manager object @PersistenceContext EntityManager em; • Binding of name @Stateless @PersistenceContext(name=”HelloWorldEntity”) public class HelloWorldBean implements HelloWorld { @Resource SessionContext context; public void hello() { EntityManager em = (EntityManager)context.lookup(“HelloWorldEntity”); } }
StateFul Session EJBs Activation and Passivation Callbacks • @PrePassivate annotate a Stateful Session EJB method as a callback that is called just before the EJB is passivated @Stateful public class AstatefulBean { ... @PrePassivate public void passivate() { // close socket connections, ... } }
StateFul Session EJBs Activation and Passivation Callbacks • @PreActivate annotate a Stateful Session EJB method as a callback that is called just before the EJB is activated @Stateful public class AstatefulBean { ... @PreActivate public void passivate() { // open socket connections, ... } }
Session EJBs Construction and Destruction Callbacks • @PreConstruct annotate a method as a callback called right after a new instance of a bean class is created by the container • can be used for initializations needed by the Bean • @PreDestroy annotate a method as a callback called right before a bean class is destroyed • can be used to free allocated resources