Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session Beans Objectives Introduction to Session Beans Local and Remote Session Beans Stateless and Stateful Session Beans Session Bean Lifecycle Accessing.

Similar presentations


Presentation on theme: "Session Beans Objectives Introduction to Session Beans Local and Remote Session Beans Stateless and Stateful Session Beans Session Bean Lifecycle Accessing."— Presentation transcript:

1 Session Beans Objectives Introduction to Session Beans Local and Remote Session Beans Stateless and Stateful Session Beans Session Bean Lifecycle Accessing Session Beans

2 Introduction to Session Beans Session beans represent a client's interaction with an enterprise application. Session beans can be accessed by Servlets, other Enterprise JavaBeans (EJB), or even desktop applications. Session beans encapsulate business methods and provide an interface for client code. A session bean typically represents a single client's interaction with the application and plays the role of the Controller in the MVC design pattern. To accommodate the different ways clients interact with applications, session beans come in two varieties: stateful and stateless.

3 EJB Container Overview 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 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.

4 Session Beans In EJB Architecture

5 Local and Remote Interfaces Local beans are meant to be accessed from within the same container. Remote session beans, as the name implies, may be accessed from remote sources. Remote session beans can be accessed through the Java Naming and Directory Interface (JNDI), a directory service provided by the EJB container. Remote beans can also be accessed locally. Remote or local access can be defined by the session bean's interface using the @Remote or @Local annotations.

6 Stateless Session Beans A stateless session bean is a session bean that does not maintain state information across multiple calls. Stateless session beans can be pooled by the EJB container.

7 Stateful Session Beans A stateful session bean keeps its internal state between invocations from the client. The stateful session beans will be less efficient because the EJB container cannot simply grab the next available session bean and hand it to the client. The client must be matched with the same bean instance that serviced the last request from the client. The state that the session bean maintains is the internal state of the object.

8 (cont.) J2EE EJB architecture

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 (remote or local) that clients can run the business logic operations via this interface without knowing the detail implementation behind the interface.

10 EJB Components (cont.) Each EJB component has a home 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 classes behind home and remote (or local) interfaces are the implementations of these two interfaces.

11 EJB Components (cont.) 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 by which client can create an instance of this EJB server component. Finally, the client invokes the business methods of this EJB instance. The EJB implementation class may also locate and access other EJB beans at remote sites by using EJB context information.

12 The Client access to EJB on server

13 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.

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

15 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. stateless session beans and stateful session beans.

16 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.

17 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. 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.

18 (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.

19 (cont.) A client requests a new session bean instance by create() method of bean home interface, and the container calls the class’s newInstance() method to create a new bean object ; the container then calls the setSessionContext() method to pass in the context environment object; it calls back the ejbCreate() method to initialize the instance. programmers can define EJB container callback method ejbCreate() which is only called once during any stateless session bean life cycle. 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.

20 Life Cycle of a Stateless Session Bean

21 Stateless session beans have the advantage of being able to be pooled. Since no state is saved with the session, there is no need to match a specific instance of the bean to a particular client. If subsequent calls are serviced by different instances, the client application does not know (or care). As a result, the total number of session bean instances may be smaller than the total number of clients accessing the application without impacting performance.

22 Your first Stateless Session Bean(2.X) This stateless session bean 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.*; public interface F2C extends EJBObject { public double fToC(double f) throws RemoteException; }

23 (cont.) //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; }

24 (cont.) 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.

25 Bean Class //The file F2CBean.java specifies the EJB implementation class. 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; } // 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) {} }

26 Client of Stateless Session Bean Web JSP client for this stateless session bean EJB component //index.jsp file. <%@ 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");

27 (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()); }

28 (cont.) public void jspDestroy() { conv = null; } %> Temperature Converter Temperature Converter Enter a temperature in Fahrenheit degree:

29 (cont.) <% 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 ) { %> in Fahrenheit degree is equivalent to in Celsius degree. <% } %> <% } %>

30 (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.look up(“ java:comp/env/ejb/myBean"),F2CHome.class);

31 (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");

32 (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. Client gets the input from clients via index.jsp 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.

33

34

35 Stateless Session Bean(EJB3.X) Session Bean Interface: package com.datavikings.sessionbeans; import javax.ejb.Remote; @Remote public interface HelloSessionRemote { String hiThere(String name); }

36 Sample Stateless Session Bean Implementation (cont.) package com.datavikings.sessionbeans; import javax.ejb.Stateless; @Stateless public class HelloSessionBean implements HelloSessionRemote { public String hiThere(String name) { return "Hi there, " + name + "!"; }

37 package com.datavikings.servlet; import com.datavikings.sessionbeans.HelloSessionRemote; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { @EJB HelloSessionRemote greeter; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

38 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if(request.getParameter("name") != null) { out.println(greeter.hiThere(request.getParameter("name ")) + " "); } out.println(" "); out.println("Your name: "); out.println(" "); out.close(); }

39 (cont.) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

40 (cont.) As the examples show, a session bean is very similar to a POJO (Plain Old Java Object). The only differences are the annotations, without which the example could easily be a plain Servlet application with a helper class. The @Remote annotation in the interface tells the EJB container that the session bean can be accessed remotely with this interface. We could have used @Local, but (as stated previously) the remote interface gives us more flexibility should the application need to scale in the future.

41 The @Stateless annotation in the session bean implementation tells the EJB container that we are not interested in keeping the state of the session bean and that it should not worry about trying to match it with a particular client. The @EJB annotation is a signal that the interface we used is actually an EJB and as such will be injected by the EJB container. This is the simplest way to access a session bean, by injecting it into a data member of the client object.

42 The Stateful Session Bean A stateful session bean keeps its internal state between invocations from the client. It seems pretty obvious, but there are some consequences that must be understood. First, the stateful session beans will be less efficient because the EJB container cannot simply grab the next available session bean and hand it to the client. The client must be matched with the same bean instance that serviced the last request from the client. If no such bean exists, a new one must be created to handle the client (and only that client). As a result, there will be as many stateful session beans as there are clients. Contrast this with the stateless bean, which can be pooled, and reduces the total number of instantiated objects and thus conserves memory.

43 The Stateful Session Bean The state that the session bean maintains is the internal state of the object. This should not be confused with the Java Persistence API, which makes data persistent by writing it to a database. If the application is shut down or the server running the EJB container loses power, the session bean ceases to exist. Rather, it is a way to keep track of the conversational state between the application and a client. It is sort of like remembering someone's name for the duration of a phone call rather than writing their name down in your address book to keep permanently.

44 The Stateful Session Bean A stateful session bean maintains a specific internal state that corresponds to a particular client session; they cannot be pooled. An analogy: When you get ready to leave, you expect the valet to bring you the car that belongs to you, not just any car in the lot stateless session beans can. An analogy of this would be eating dinner at a fancy restaurant. If you ask the waiter for a fork he will bring you one from a “pool” of forks, because they are all pretty much the same.

45 The Stateful Session Bean Because of this, the stateful session bean must exist for the duration of the client session in case the client needs it again. EJB container decides to“passivate,” or serialize a stateful session bean and place it in a more long-term storage area in order to free some memory. Before a passivated session bean can service the client the EJB container must locate it and unserialize it to place it back in memory.

46 The Life Cycle of a Stateful Session Bean Life Cycle of a Stateful Session Bean

47 Your First Stateful Session Bean(2.x) simple on-line shopping cart with 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)

48 Your First Stateful Session Bean 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

49 Your First Stateful Session Bean (cont.) The CartHome.java is a Home interface file for this statefull 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;}

50 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; }

51 Your First Stateful Session Bean (cont.) //The CartBean.java is a stafull session bean class file which implement 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; //ejbCreate() is called back by EJB container after clients invoke //create() method. It creates a vector to hold all shopped items public void ejbCreate(String name) throws CreateException { if (name == null) { throw new CreateException("creation failed."); } else { this.name = name; } cart = new Vector(); }

52 Your First Stateful Session Bean (cont.) //Add an new item to the cart public void addItem(String item) { cart.add(item); } //Remove an existing item from the cart public void removeItem(String item) throws RemoteException { boolean result = cart.remove(item); if (result == false) { throw new RemoteException(“Can’t find it”); } } //Return this cart public Vector getCart() { return cart; } public CartBean() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {sessionContext=sc ;} // sessionContext is useful when this session needs to use //other resources in the session context} }

53 Stateful Session Bean EJB3.x Example package com.datavikings.sessionbeans; import javax.ejb.Remote; @Remote public interface HelloSessionRemote { String hiThere(String name); } Stateful Session Bean Implementation: package com.datavikings.sessionbeans; import javax.ejb.Stateful; @Stateful(mappedName=”HelloSessionBean”) public class HelloSessionBean implements HelloSessionRemote { String name = null;

54 (cont.) public String hiThere(String n) { if(name == null) { name = n; return "Hi there, " + name + ". It's nice to meet you";} else { return "Hey, I remember you! Your name is " + name + "!"; }

55 Sample Servlet Client: package com.datavikings.servlet; import com.datavikings.sessionbeans.HelloSessionRemote; import java.io.IOException; import java.io.PrintWriter; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HelloSessionRemote greeter = null; try {InitialContext ctx = new InitialContext(); if(request.getSession().getAttribute("greeter") == null) { greeter = (HelloSessionRemote) ctx.lookup("HelloSessionBean");

56 request.getSession().setAttribute("greeter", greeter);} else {// Otherwise, get reference from session greeter = (HelloSessionRemote) request.getSession().getAttribute("greeter");} } catch(NamingException e) {e.printStackTrace();} if(request.getParameter("name") != null) { out.println(greeter.hiThere(request.getParameter("name")) + " "); } out.println(" "); out.println("Your name: "); out.println(" "); out.close(); }

57 (cont.) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }


Download ppt "Session Beans Objectives Introduction to Session Beans Local and Remote Session Beans Stateless and Stateful Session Beans Session Bean Lifecycle Accessing."

Similar presentations


Ads by Google