Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Web Development with NetBeans IDE --Kai Qian Chapter 6 Session Beans Objectives • • • • • Introduction to Session Beans Local and Remote Session Beans Stateless and Stateful Session Beans Session Bean Lifecycle Accessing Session Beans 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. Container Overview • The EJB container provides services like security and transaction management to the EJB deployed in it. • The EJB container is constantly running, managing lifecycles, allocating resources, and providing services for EJB. • If the session beans are the building blocks and the program is the blueprint, the container is the construction foreman who makes everything happen on time. • Once the application is written, it is deployed to the container. Session Beans In EJB Architecture 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. 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. 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. EJB Architecture and J2EE platform • 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. (cont.) • The EJB architecture makes Web enterprise application development much easier because most of system level services such as transaction 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. (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 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). (cont.) app server site2 Entity Bean db servlet session bean HTML JSP web server client-tier web-tier app server site1 business-tier J2EE EJB architecture Entity Bean app server site3 db data-tier 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 • 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. 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. 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. 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. 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. 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. 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. 1.Lookup(“EJB”) JNDI Registers with Client 2,Create() EJB Home Interface New() 3. Invoke method EJB Class EJB Object Interface EJB Context EJB container (security, transaction, life cycle, persistence) EJB The Client access to EJB on server Server EJB Components (cont.) 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 document which 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. 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. • The EJB implementation class implements either sessionBean or entityBean interface, both of that implement EnterpriseBean interface Java.ejb.EnterpriseBean Javax.ejb.EntityBean Javax.ejb.SessionBean EntityBean SessionBean EJB implementation class hierarchy 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 nonpersistent. • 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. 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. 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. • The EJB container may instantiate session beans when the server starts. (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. (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. • programmers can define EJB container callback methods . 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. • 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. Not Exist create() remove() Class.newInstance() ejbRomove() setSessionContext() ejbCreate() (only once) business method invocation Method Ready Life Cycle of a Stateless Session Bean • 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. Your first Stateless Session Bean(2.X) • 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.*; (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; } (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. (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; } (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) {} } Client of Stateless Session Bean • 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.F2C,f2c.F2CHome,javax.ejb.*, java.rmi.RemoteException, javax.naming.*,javax.rmi.*, java.text.DecimalFormat" %> <%! private F2C conv = null; public void jspInit() { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/myBean"); (cont.) F2CHome home = (F2CHome)PortableRemoteObject.narrow(objRef, F2CHome.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()); } } (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"> (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> (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); (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"); (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. Stateless Session Bean(EJB3.X) Session Bean Interface: package com.datavikings.sessionbeans; import javax.ejb.Remote; @Remote public interface HelloSessionRemote { String hiThere(String name); } 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 + "!"; } } Sample Servlet Client: 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; Client(cont.) 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 { (cont.) response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if(request.getParameter("name") != null) { out.println(greeter.hiThere(request.getParameter("nam e")) + "<br />"); } out.println("<formmethod=\"post\" action=\"HelloServlet\">"); out.println("Your name:<input type=\"text\" name=\"name\" />"); out.println("<input type=\"submit\" value=\"Say Hi\" />"); out.println("</form>"); out.close(); } (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); } } (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); } } (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. • 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. 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. 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. It is not a long-term storage solution. 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. The Stateful Session Bean • The lifecycle of a stateful session bean is more complicated than its stateless sibling. Because each session bean maintains a specific internal state that corresponds to a particular client session, they cannot be pooled the way 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. The Stateful Session Bean • When you get ready to leave however, you expect the valet to bring you the car that belongs to you, not just any car in the lot. Because of this, the stateful session bean must exist for the duration of the client session in case the client needs it again. If the EJB container decides that it needs to conserve some memory, it may “passivate,” or serialize a stateful session bean and place it in a more longterm 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. The Life Cycle of a Stateful Session Bean Life Cycle of a Stateful Session Bean Your First Stateful Session Bean(2.x) • 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) 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 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;} 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; } 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; 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 //here is 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(); } 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”); } } Your First Stateful Session Bean (cont.) //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} Stateful Session Bean(EJB3.X) Session Bean Interface: 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; 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 + "!";} } } 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.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; (cont.) 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"); (cont.) 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")) + "<br />"); } out.println("<form method=\"post\" action=\"HelloServlet\">"); out.println("Your name:<input type=\"text\" name=\"name\" />"); out.println("<input type=\"submit\" value=\"Say Hi\" />"); out.println("</form>"); out.close(); } (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); } }