objectives of this chapter n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Objectives of This Chapter PowerPoint Presentation
Download Presentation
Objectives of This Chapter

play fullscreen
1 / 273

Objectives of This Chapter

133 Views Download Presentation
Download Presentation

Objectives of This Chapter

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Objectives of This Chapter • Overview • Session Beans • Entity Beans • Message Driven beans • EJB Web service • The Deployment Model of EJB • Examples and Lab Practice

  2. Overview • Overview of the EJB Architecture and J2EE platform • The new specification of Java EJB 2.1 was released by Sun Microsystems Inc. in 2002. • The EJB technology is widely used for large scale distributed applications where the resources, data, and users are distributed. Such distributed applications usually require system scalability and transaction managements for data integrity. • An EJB component is a reusable, WORA (Write Once Run Anywhere), portable, scalable, and compiled software component which can be deployed on any EJB servers such as Java 2 Platform Enterprise Edition (J2EE), JBoss, and WebLogic Enterprise environment. • The Java EJB technology is part of J2EE which provides a set of APIs, and other system services. The EJB implementations concentrate on business logic. • J2EE is a enterprise reference architecture for Java enterprise applications. J2EE not only supports EJB components but also supports other Web components such as JSP and Servlets.

  3. Overview of the EJB Architecture and J2EE platform (cont.) • The EJB architecture makes Web enterprise application development much easier because most of system level services such as transaction management, security management, and multithreading management are supported by the EJB container instead of applications themselves. • The EJB architecture also manages the EJB component lifecycle from the creation to the termination including activation and deactivation of an EJB component. • An EJB component is a server side component which provides services to remote Web clients or local and remote application clients.

  4. Overview of the EJB Architecture and J2EE platform (cont.) • Web clients access this application via a Web browser in the client tier; The services may be provided by Java Servlets or JSPs on Web servers in the Web tier; The Servlets or JSPs need to access services provided by EJB beans located on remote distributed application servers in the business tier; The business tier is supported by databases in the Enterprise Information System (EIS) data tier. • The Web servers, application servers, and data servers may be all located in different locations connected by Internet. The EJB technology is suitable for developments of very large and complex distributed applications such as business to business (B2B).

  5. Overview of the EJB Architecture and J2EE platform (cont.) J2EE EJB architecture

  6. EJB Container • All EJB instances are running within the EJB container. The container is a runtime environment (set of classes generated by deployment) that controls an EJB component instance and provides all necessary management services for its whole lifetime. Below is a list of such services: • Transaction management: ensuring transaction properties of multiple distributed transaction executions. • Persistence management: ensuring a persistent state of an entity bean that is backed up by database. • Life cycle management: ensuring the EJB component state transitions in its life cycle. • Security management: authentication and authorization services, integrity, and encryption management.

  7. EJB Container (cont.) • All access requests to the EJB component and responses from the EJB component must get through the EJB container. • The EJB container is a run time environment which isolates EJB component from direct access by its clients. • The container will intercept the invocation from clients to ensure the persistence, properties of transaction, security of client operations on EJB.

  8. EJB Container (cont.) • The EJB container supports all services EJB components need and an EJB component needs the container to reach outside and to obtain necessary information from its context interface. • The EJB container is in charge of generating an EJB home object, which helps to locate, create, and remove the EJB component object. • The EJB context interface provided by the EJB container encapsulates relevant information of the container environment and initialization parameters.

  9. EJB Components • An enterprise bean is a distributed server component that lives in an EJB container and is accessed by remote clients over network via its remote interface or is accessed by other local enterprise beans on the same server via its local interface. • The EJB component is a remotely executable component deployed on its server and it is a self-descriptive component specified by its Deployment Descriptor (DD) in a XML format. • Each EJB component has a business logic interface that clients can run the business logic operations via this interface without knowing the detail implementation behind the interface.

  10. EJB Components (cont.) • We call such interface as a remote or local interface. An instance of an EJB component is created and managed by its factory named home interface on the EJB container. • Every enterprise bean must have a home interface and a remote (local) interface. The EJB component can be configured at the deployment time by specifying its deployment descriptor.

  11. EJB Components (cont.) • The EJB classes behind home and remote (or local) interfaces are the implementations of these two interfaces. • An EJB component is a black-box component. A client of an EJB component only knows what the component does but not how it does. • A client makes a request to an EJB component with its deployed name by looking up at JNDI to get an Object Reference (OR) of this EJB component.

  12. EJB Components (cont.) • The client can then create an instance of this EJB component on the server according to the reference. Finally, the client invokes the business methods of this EJB instance. • The EJB class may also locate and access other EJB beans at remote sites by using EJB context information. • The message driven bean is an exception which does not have any interface like the home and remote interfaces that a classic EJB has.

  13. The Client access to EJB on server

  14. EJB Components (cont.) • The EJB technology supports the following enterprise bean categories: • Session Bean • Stateless session beans that implement various business logics, such as language translation, logon process, tax calculation, and currency conversion • Stateless session beans that is wrapped in a Web service Any existing enterprise bean can be encapsulated in an external web service by a WSDL documentwhich describes the web service endpoint of the bean implementations. Such special bean does not provide interfaces that a regular EJB component provides. • Stateful session beans, which play the same roles as stateless session beans except they keep tracking the states of the conversation during a session. For instance, a shopping cart bean can be a typical stateful session bean. • A session bean does not have its permanent state.

  15. Entity Bean • Bean Managed Persistence (BMP) entity beans, where persistent storage management (JDBC SQL) is coded by bean developers. . • Container Managed Persistence (CMP) entity beans, where the persistent storage management is specified by the deployment tool and managed by the container. • An entity bean is backed up by a relational database.

  16. Message-Driven Beans (MDB) • MDB represents a new EJB component type that works in an asynchronous communication mode just like an event-driven delegation model in Java. EJB interfaces

  17. Message-Driven Beans (MDB) (cont.) • The Remote interface of an EJB component implements javax.ejb.EJBObject interface which in turn implements java.rmi.Remote interface. The Home interface of an EJB component implements javax.ejb.EJBHome interface which again implements java.rmi.remote interface. • A local interface implements javax.ejb.EJBLocalObject interface and a local home interface implements javax.ejb.EJBLocalHome interface. The local interface is used by another EJB component running on the same server so that it can reduce the overhead caused by remote access.

  18. Message-Driven Beans (MDB) (cont.) • The remote interface provides the location independence but it is more expensive since it must provide stub and skeleton to support the remote communications. • The local interface makes invocation much more efficient than remote. Another important difference between local and remote interfaces is that method invocation in local interface uses passing by reference and the method invocation in remote interface uses passing by value which needs serialization, i.e., marshaling and unmarshaling.

  19. The EJB implementation class implements either sessionBean or entityBean interface, both of that implement EnterpriseBean interface EJB implementation class hierarchy

  20. Session Beans • As its name implies, a session bean is an interactive bean and its lifetime is during the session with a specific client. It is non-persistent. • When a client terminates the session, the bean is not longer associated with the client and is terminated as well. • A server site session bean represents a particular client. It responses on behalf of a client and terminates when the client session is over. • Session beans are often designed for major and complex business logic and flow control in front of entity beans. • A session bean may control the dialogues with entity bean business objects. They may also make requests to another session bean or to other Web components such as JSP, Servlet, or HTML pages. • There are two session bean types: stateless session beans and stateful session beans.

  21. Stateless Session Bean • The stateless session bean simply defines a set of independent operations that can be performed on behalf of clients. • A stateless session bean plays a role of controller and perform some procedural operation on behalf of client during its session.

  22. Life Cycle of a Stateless Session Bean • The life cycle of a stateless session bean is very simple since it does not need to keep any state and lives only during the session. Its life cycle has only two stages: not-exist and method ready for the invocation of business methods. Illustrates the stages of the life cycle for a stateless session bean. • The not-exist stage basically is where the bean interface and class files are located. The method stage is where the instantiated bean instance is loaded into memory. • The EJB container may instantiate session beans when the server starts.

  23. Life Cycle of a Stateless Session Bean (cont.) • The EJB container manages a bean instance pool to reduce the number of component instantiations so that expenses on the creations and removals of bean instances can be significatelly reduced. • There are two type methods in a enterprise bean: the business methods and the bean life cycle methods. • The business methods are called by clients and life cycle methods ( callback) methods are called back by the EJB container when the EJB container thinks it is necessary. • The EJB callback methods are underlined in the diagram and others are notated in the boxes.

  24. Life Cycle of a Stateless Session Bean (cont.) • A client requests a new session bean instance by create() method of bean home interface, and the container calls the class’s mewInstance() method to create a new bean object ; and then the container calls the setSessionContext() method to pass in the context environment object; it calls back the ejbCreate() method to initialize the instance. • The last two methods are the EJB container callback methods which programmers can define. At this time this session bean is in its method ready pool stsge and ready to respond client method invocation. The ejbCreate() method is only called once during any stateless session bean life cycle.

  25. When the remove() method is called the ejbRemove() is then called next; the bean may be pulled out from the ready stage and is back to not-exist stage. [1][2][3] Life Cycle of a Stateless Session Bean

  26. Your first Stateless Session Bean • In this section we demostrate a simple stateless session bean which performs a temperature conversion from a Fahrenheit temparature to its Ceilcius temparature. First, two interfaces ( Home interface and Remote interface) are specified in F2CHome.java and F2C.java files perspectively. //F2C.java specifies remote interface for this converter session bean //It exposes the business method fToC() package f2c; import javax.ejb.EJBObject; import java.rmi.RemoteException; import java.math.*;

  27. Your first Stateless Session Bean (cont.) public interface F2C extends EJBObject { public double fToC(double f) throws RemoteException; } //The file F2CHome.java specifies the home interface for this EJB package f2c; import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface F2CHome extends EJBHome { Converter create() throws RemoteException, CreateException; }

  28. Your first Stateless Session Bean (cont.) • Second, we define the implementation of this stateless session bean in the F2CBean.java file. • The fToC() method implementation is specified in this file; the declaration of this method is listed in its remote interface. • Notice that this bean class does not have its own state property. It simply takes client inputs and performs the conversion operations, and then returns the results. It specifies the implementations of the EJB interfaces listed above. • After it completes its service it will not remember what happened in the past.

  29. Your first Stateless Session Bean (cont.) //The file F2CBean.java specifies the EJB implementation class //for above interfaces of this EJB component. package f2c; import java.rmi.RemoteException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import java.math.*; public class F2CBean implements SessionBean { public double fToC(double f) { double temp=(f-32)*5./9; return temp; }

  30. Your first Stateless Session Bean (cont.) // It must have a default constructor; All EJB container //call back methods are also listed public F2CBean() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} }

  31. Your first Stateless Session Bean (cont.) • Finally, we develop a Web JSP client for this stateless session bean EJB component in the index.jsp file. <%-- Web Client for the EJB: index.jsp --%> <%@ page import="f2c.TempConv,f2c.TempConvHome,javax.ejb.*, java.rmi.RemoteException, javax.naming.*,javax.rmi.*, java.text.DecimalFormat" %> <%! private TempConv conv = null; public void jspInit() { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/myBean");

  32. Your first Stateless Session Bean (cont.) TempConvHome home = (TempConvHome)PortableRemoteObject.narrow(objRef, TempConvHome.class); conv = home.create(); } catch (RemoteException ex) { System.out.println("Couldn't create bean."+ ex.getMessage()); } catch (CreateException ex) { System.out.println("Couldn't create bean."+ ex.getMessage()); } catch (NamingException ex) { System.out.println("Unable to lookup home: "+ "myBean "+ ex.getMessage()); } }

  33. Your first Stateless Session Bean (cont.) public void jspDestroy() { conv = null; } %> <html> <head> <title>Temperature Converter</title> </head> <body bgcolor="white" ><center> <h4><b>Temperature Converter</b></h4> <p>Enter a temperature in Fahrenheit degree:</p> <form method="get"> <input type="text" name="degree" size="25"> <br> <p> <input type="submit" name="fToC" value="Fahrenheit to Celsius">

  34. Your first Stateless Session Bean (cont.) </form> <% DecimalFormat twoDigits = new DecimalFormat ("0.00"); String degree = request.getParameter("degree"); if ( degree != null && degree.length() > 0 ) { double d = Double.parseDouble(degree); %> <% if (request.getParameter("fToC") != null ) { %> <p> <%= degree %> in Fahrenheit degree is equivalent to <%= twoDigits.format(conv.fToC(d)) %> in Celsius degree. <% } %> <% } %> </center></body> </html>

  35. Your first Stateless Session Bean (cont.) • Web clients of this application locate the home object of this session bean by the Java Naming and Directory Interface (JNDI). The InitialContext class is the context for performing JNDI naming operations. The lookup() method takes the bean's JNDI name “myBean” (deployed name) as the argument: Context initialContext = new InitialContext(); F2CHome home = (F2CHome)PortableRemoteObject.narrow(initialContext.lookup(“ java:comp/env/ejb/myBean"),F2CHome.class);

  36. Your first Stateless Session Bean (cont.) • The PortableRemoteObject.narrow() method must be used in order to access a remote bean object via JNDI lookup. • This method converts the RMI-IIOP compatible remote home stub into a Java object. • For a local clients, the client and EJB bean are in the same server, the return value of the InitialContext.lookup() method is not a stub and you can directly cast it to the local home interface just like the following statement. LocalF2CHome home = (LocalF2CHome)initialContext.lookup("java:comp/env/ejb/myBean");

  37. Your first Stateless Session Bean (cont.) • The detail procedures of the compilation, configuration, deployment of this session bean and its Web client can be found in the section 6.7 Examples and Lab Practice. The following screen shots illustrate this stateless session bean Web application which converts 32 Fahrenheit degrees to 0 Celsius degrees. • Client can use any Web browsers to browse the index.jsp JSP page which is the default JSP page that you don’t even need to include it as your URL; the index.jsp gets the input from clients and locates this session EJB; it then gets the required services from the bean and display the converted temperature on the page. • This is a simplest Web application of a stateless Java enterprise session bean.

  38. The Stateful Session Bean • Overview • A stateful session bean represents a specific client and holds related data for this client during the session. For example, a shopping cart session bean or a student registration session bean is stateful because the session must keep track of which items or courses have been selected so far. • A session bean class may have a Collection type data member pertaining to the client during a session but it does not have any permanent data storage to support. The operations of a stateful EJB are context dependent which use and update the state data and the operations are performed on behalf a client. • A stateful session bean is not supposed to be shared by multiple clients but it keeps its data for a client in many request transactions within a same session.

  39. The Life Cycle of a Stateful Session Bean Life Cycle of a Stateful Session Bean

  40. The Life Cycle of a Stateful Session Bean (cont.) • The life cycle of a stateful session bean is more complicated than a staeless session bean in that it has an additional inactive pool state. The main flow of the life cycle is as follows. • Clients invoke bean’s home create() method in client application via the stub, EJB container instantiates a instance, calls the setSessionContext() and ejbCreate() methods, and move it in the method reay stage. • The EJB container may instantiate a number of bean instances when the server starts. While in the method ready stage, the EJB container may passivate the bean by calling ejbPassivate() to move it from memory to secondary storage following a least-recently-used(LRU) rule.

  41. The Life Cycle of a Stateful Session Bean (cont.) • If a client invokes a business method of the bean while it is in the passive stage, the EJB container activates the bean, calls the bean's ejbActivate() method, and then moves it to the method ready stage. • When a client invokes the remove() method, the EJB container calls the bean's ejbRemove() method. • All the methods whose name with ejbXXX are invoked by the EJB container. The ejbCreate() method, for example, is inside the bean class, lets you perform certain initiazation operations such as database connection right after the bean is instantiated.

  42. The Life Cycle of a Stateful Session Bean (cont.) • There are three ways for a stateful session bean to move in the method ready stage. The EJB container allocates and instantiates the instance when the server starts or when clients invoke the create() method causing the EJB container to call the ejbCreate() and ejbPostCreate() methods , or the EJB container invokes the ejbActivate() method when it is needed.. • While a bean is in the method ready stage, an it's business methods can be invoked. • There are two ways to move beans away from the method ready stage. Clients can invoke the remove() method, which causes the EJB container to call the ejbRemove() method. Second, the EJB container can invoke the ejbPassivate() method.

  43. Your First Stateful Session Bean • You will see a simple on-line shopping cart stateful session bean class with its Home interface and Remote interface. • This stateful session been has a vector data state which is a cart holding all the items customer put in during the shopping session. • The customer can also remove any items from this cart and review the cart during that session. • Home interface (CartHome) • Remote interface (Cart) • Session bean class (CartBean)

  44. Your First Stateful Session Bean (cont.) • The home interface is like an EJB factory that defines the create() methods and clients may invoke it to create a new instance of the bean. For example, clients call this create() method: • Cart myCart = home.create(“Allen”); • Every create() method in the home interface has its corresponding ejbCreate() callback method in the bean class. The signatures of the ejbCreate() methods in the CartBean class is as follows. • public void ejbCreate(String name) throws CreateException

  45. Your First Stateful Session Bean (cont.) • The CartHome.java is a Home interface file for this stateless session bean. This home interface extends the javax.ejb.EJBHome interface. package shoppingCart; import java.rmi.RemoteException; import javax.ejb.*; public interface CartHome extends EJBHome { Cart create(String name) throws RemoteException, CreateException;}

  46. Your First Stateful Session Bean (cont.) • The Cart.java is a Remote interface file which declares all business methods that the CartBean implements. This Remote interface extends javax.ejb.EJBObject, and defines the business methods that a remote client may invoke. package shoppingCart; import java.util.*; import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Cart extends EJBObject { public void addItem(String item) throws RemoteException; public void removeItem(String item) throws RemoteException; public Vector getCart() throws RemoteException; }

  47. Your First Stateful Session Bean (cont.) • The CartBean.java is a stafull session bean class file which implements all bean interface and overrides the container callback methods. package shoppingCart; import java.util.*; import javax.ejb.*; import java.rmi.*; public class CartBean implements SessionBean { String name; Vector cart; SessionContext sessionContext;

  48. Your First Stateful Session Bean (cont.) //ejbCreate() is called back by EJB container after clients invoke //create() method. Some initialization is done here. The main job //hereis to create a vector to hold all shopped items for this cart. public void ejbCreate(String name) throws CreateException { if (name == null) { throw new CreateException("creation failed."); } else { this.name = name; } cart = new Vector(); }