720 likes | 996 Views
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.
E N D
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.
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.) J2EE EJB architecture
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.
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 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 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.
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 defineEJB 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. 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.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");
(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()); } }
(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.lookup(“ 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("name")) + "<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); } }