Download presentation
Presentation is loading. Please wait.
Published bySibyl McDowell Modified over 9 years ago
2
1 Session Beans and Business Logic Presented By: Sethu Ram Kettimuthu
3
2 For Starters..
4
3 A look at the ‘Forest’ What is a middle ware? Middleware is a layer of software between the network and the applications that provides services such as identification, authentication, authorization, directories, and security. By promoting standardization and interoperability, middleware will make advanced network applications much easier to use.
5
4 Trees of the Forest CORBA
6
5 Corba (Contd) The CORBA specification only defines a set of conventions and protocols that must be followed by CORBA implementations CORBA does not make any restrictions on language or underlying operating system Because of CORBA's heterogeneous nature, a neutral language was needed to perform the task of defining the interfaces to ORB-based objects You can implement IDL interfaces using any programming language for which an IDL mapping is available
7
6 E-Speak Fundamentally e-speak is a distributed development environment, just like Java/RMI, just like CORBA, just like the Web itself To access a service, a client: Creates a connection to the e-Speak engine Identifies a contract and vocabulary to use when searching for services Locates the service using ESServiceFinder Invokes the methods specified by the service interface
8
7
9
8
10
9.Net & Com+ With.NET—Microsoft's new Web services platform—your applications, services, and devices work together to provide access to the information you need at anytime and any place.net is MS equivalent of J2EE Com+ is MS equivalent of EJB C# is MS equivalent of Java
11
10 Now to EJB..at last Why EJB? EJB enables rapid development of mission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in What is EJB? Enterprise beans are server components written in the Java programming language. Enterprise beans contain the business logic for your application. For example, a checkbook client might invoke the debit and credit methods of an account enterprise bean
12
11 FeatureEJBCOM+ Component LanguageJava only All (Java: unclear future) PlatformsAllWindows 2000 Middleware Vendors30+Microsoft Legacy Integration RMI/JNI, CORBA, Connectors (future) COM TI, MSMQ, OLE DB ProtocolAny (future: IIOP)DCOM Stateless componentsYes Stateful componentsYesNo Persistent componentsYesNo Queued componentsNoYes Middleware comes with OS NoYes Cluster-wide processors Theoretically unlimited Development toolsChoice of manyMicrosoft Dev Studio
13
12 key features of the EJB technology EJB components are server-side components written entirely in the Java programming language EJB components contain business logic only System-level services are automatically managed for the EJB component by the EJB server EJB components are fully portable across any EJB server and any OS
14
13 Types of enterprise beans Session Beans (More on Session Beans rest of the seminar) Entity Beans - An entity bean represents a business object in a persistent storage mechanism such as a database - May be shared by multiple clients - Persistent - even when the EJB container terminates, the entity state remains in a database.
15
14 Session Beans Purpose : Performs a task for a client Shared Access : May have one client Persistence : Not persistent. When the client terminates its session bean is no longer available.
16
15 Session Beans – Contd.. The client accesses remote services by invoking the session bean's methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server It is similar to an interactive session The Session Beans Terminates with the client Session beans are powerful because they extend the reach of your clients into remote servers-- yet they're easy to build
17
16 How to Write Session Beans To write a session enterprise bean class, the class must implement the javax.ejb.SessionBean interface The javax.ejb.SessionBean interface extends the more generic javax.ejb.Enterprise Bean interface So does the javax.ejb.EntityBean
18
17 Methods in SessionBean Interface Javax.ejb.SessionBean Interface Public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean { public abstract void setSessionContext(SessionContext ctx) throws java.rmi.RemoteException; public abstract void ejbPassivate() throws java.rmi.RemoteException; public abstract void ejbActivate() throws java.rmi.RemoteException; public abstract void ejbRemove() throws java.rmi.RemoteException; }
19
18 A look at each method setSessionContext(SessionContext ctx) Container calls this method to associate the bean with a session context A session context is the bean’s gateway to interact with the container The bean can use the session contexts to query the container about the current transactional state,security state etc..
20
19 A look at each method ejbCreate(..) Initializes the session bean Can define one or more ejbCreate() methods and each can take different arguments Can perform any initialization the bean needs,ie., public class MyBean implements SessionBean { private int memberVar; public void ejbCreate(int init val) { this.memberVar = initval; } …. }
21
20 A look at each method ejbPassivate() If too many beans are instantiated, the EJB container can passivate some of them(by writing the beans to a temp storage like a DB or File) The container can then release the Resources the beans had claimed Immediately before the Beans are passivated the container calls the ejbPassivate() method NOTE: Remember that passivation doesn’t apply to stateless bean as it cannot hold the state.
22
21 A look at each method ejbActivate() When a client needs to use the passivated bean then the container ‘kicks’ the bean back into memory. This is activation. Once the bean is back in the memory again, the beans implementation acquires any resource the bean needs. NOTE: Activation doesn’t apply to stateless session beans as it cannot hold state and can simply be created/destroyed rather than passivated/activated
23
22 Guess who spoke this "You've heard Al Gore say he invented the internet. Well, if he was so smart, why do all the addresses begin with "W"?“ Any body …?
24
23 A look at each method ejbRemove() When the container is about to remove your session bean instance it calls the bean’s ejbRemove() method ejbRemove is a clean-up method, alerting the bean that it is about to destroyed. ejbRemove() is a required method of all beans and takes no parametrs. There is only one ejbRemove() method per bean.
25
24 A look at each method Business Methods: There can be zero or more Business methods in your bean These methods actually solve business problems For eg: public class MyBean implements SessionBean { public int add(int I,int j) { return(I + j) ;} …} For clients to call your business methods, the business methods must be listed in the bean’s remote interface
26
25 Major parts of an EJB Application Session Bean Class Home Interface Remote Interface Deployment Descriptor
27
26 Two types of State Transactional state Roughly speaking this is the data stored in the persistent store Multiple client can read and modify the data without conflict If the App Server crashes or re-started the data is still available in the data store Example: An order that a customer has placed
28
27 Two types of State Conversational State : Cached data either on the Client or Server Private data that isn’t accessible to other clients Example : The web shopping cart before the order has been confirmed REMEMBER: A stateless session bean holds conversations that span a single method call. So it doesn’t hold Conversational state, BUT stateful session bean holds Conversational state
29
28 Types of Session Beans Stateless Session Beans Stateful Session Beans (We’ll see about this later)
30
29 Stateless Session Beans(SLSB) A stateless session bean does not maintain a conversational state for a particular client When a client invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the duration of the invocation The state is not customized for each client The SLSB cannot retain state between method calls,but they also cannot retain state after a client passes data to an ejbCreate() call So all SLSB may expose only a single ejbCreate() method,which takes no parameters
31
30 Stateless Session Bean Pooling Client Remote Interface EJB Obj bean Stateless session bean pool Invoke()
32
31 ‘Hello world’ SLSB Function: The SLSB, a component running in a Distributed Environment will do the mighty task of returning the string ‘Hello World’ to the client.
33
32 ‘Hello world’ Remote Interface The remote interface is what the clients operate on when they interact with EJB objects. The container vendor will implement this interface; the implemented object is the EJB object,which delegates invocations to the actual bean import javax.ejb.*; import java.rmi.RemoteException; Import java.rmi.remote; Public interface Hello extends EJBObject { public String hello() throws java.rmi.RemoteException; }
34
33 Implementing the ‘Hello world’ bean /* Stateless Session bean */ import javax.ejb.*; public class HelloBean implements SessionBean { /* EJB required methods */ public void ejbCreate( ) { System.out.println(“Create Method”);} public void ejbremove( ) { System.out.println(“Remove Method”);} public void setSessionContext(SessionContext ctx) {System.out.println(“Set Session Context”);} // Business Methods public String hello() { System.out.println(“Hello()”); return “Hello World”;} }
35
34 ‘Hello World’ Home Interface The Home Interface for HelloBean is implemented by the EJB Server’s glue-code tools- the implemented object is called the Home Object and serves as the factory for EJB Objects import javax.ejb.*; import java.rmi.RemoteException; /* One create() method is in this Home INTERFACE */ public interface HelloHome extends EJBHome { /* This method creates the EJB Object & return the newly created EJB object*/ Hello create() throws RemoteException, CreateException; }
36
35 Deployment Descriptor Deployment Descriptor SettingValue Bean Home NameHelloHome Enterprise bean class name.helloworld.HelloBean Home Interface Class name.helloworld.HelloHome Remote Interface class name.helloworld.Hello Environment Variables Re-entrantfalse Stateful or statelessSTATELESS_SESSION Session timeout7 secs
37
36 EJB-JAR File Last step before deploying Package all the files above in an EJB-Jar file Jar files are compact modules in which to wrap our beans The files to be included are : Enterprise Bean Remote Interface Home interface Deployment Descriptor
38
37 Client pseudo-code for Stateless Bean The HelloClient class invokes methods on a simple stateless beans Get system properties for JNDI initialization Form an initial context Get a reference for the home object(factory for EJB Objects) Use the factory to create EJB Object Call the Hello() method and print the string Since the EJB object is done with, remove it /* hello.remove; */ Check for any Exception
39
38 Lifecycle of a SLSB Because a stateless session bean is never passivated, its life cycle has just two stages: non-existent and ready for the invocation of business methods.
40
39 Stateful Session Beans Stateful Session Beans are conversational beans Because they hold conversation with clients that span multiple method invocations Stateful Session Bean store conversatinal state within the bean The conversational state is specific to a particular client
41
40 Passivation of Stateful bean Remote Interface EJB Obj bean Client Passivated Bean stored
42
41 Stateful Session bean Lifecycle Does not exist ReadyPassive ejbPassivate ejbActivate 2. ejbRemobe 1.remove 1.create 2. setSessionContext 3 ejbCreate
43
42 CartEJB.java import java.util.*; import javax.ejb.*; public class CartEJB implements SessionBean { String customerName; String customerId; Vector contents; public void ejbCreate(String person) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new Vector(); }
44
43 public void ejbCreate(String person, String id) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new CreateException("Invalid id: " + id); } contents = new Vector(); }
45
44 public void addBook(String title) { contents.addElement(title); } public void removeBook(String title) throws BookException { boolean result = contents.removeElement(title); if (result == false) { throw new BookException(title + " not in cart."); } } public Vector getContents() { return contents; } public CartEJB() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} }
46
45 The SessionBean Interface The SessionBean interface extends the EnterpriseBean interface, which in turn extends the Serializable interface. The SessionBean interface declares the ejbRemove, ejbActivate, ejbPassivate, and setSessionContext methodsSessionBean
47
46 The ejbCreate Methods Because an enterprise bean runs inside an EJB container, a client cannot directly instantiate the bean. Only the EJB container can instantiate an enterprise bean. During instantiation, the example program performs these steps: 1. The client invokes a create method on the home object: Cart shoppingCart = home.create(“Sethu","123"); 2. The EJB container instantiates the enterprise bean. 3. The EJB container invokes the appropriate ejbCreate method in CartEJB
48
47 public void ejbCreate(String person, String id) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new CreateException("Invalid id: " + id); } contents = new Vector(); }
49
48 Business Methods The primary purpose of a session bean is to run business tasks for the client. The client invokes business methods on the remote object reference that is returned by the create method. From the client's perspective, the business methods appear to run locally, but they actually run remotely in the session bean. The following code snippet shows how the CartClient program invokes the business methods: Cart shoppingCart = home.create("Duke DeEarl", "123");... shoppingCart.addBook("The Martian Chronicles"); shoppingCart.removeBook("Alice In Wonderland"); bookList = shoppingCart.getContents();
50
49 The CartEJB class implements the business methods in the following code: public void addBook(String title) { contents.addElement(new String(title)); } public void removeBook(String title) throws BookException { boolean result = contents.removeElement(title); if (result == false) { throw new BookException(title + " not in cart."); } } public Vector getContents() { return contents;}
51
50 Home Interface A home interface extends the EJBHome interface. The purpose of the home interface is to define the create methods that a client may invoke. The CartClient program, for example, invokes this create method: Cart shoppingCart = home.create("Duke DeEarl", "123"); Every create method in the home interface corresponds to an ejbCreate method in the bean class. The signatures of the ejbCreate methods in the CartEJB class follow: public void ejbCreate(String person) throws CreateException... public void ejbCreate(String person, String id) throws CreateException
52
51 create methods in the CartHome interface: import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface CartHome extends EJBHome { Cart create(String person) throws RemoteException, CreateException; Cart create(String person, String id) throws RemoteException, CreateException; }
53
52 Remote Interface The remote interface, which extends javax.ejb.EJBObject, defines the business methods that a client may invoke. Here is the source code for the Cart remote interface : import java.util.*; import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Cart extends EJBObject { public void addBook(String title) throws RemoteException; public void removeBook(String title) throws BookException, RemoteException; public Vector getContents() throws RemoteException; }
54
53 You should consider using a stateful session bean if any of the following conditions are true: The bean's state must be initialized when it is created. The bean needs to hold information about the client across method invocations. The client is an interactive application. Since the primary goal of a session bean is to represent a client in the J2EE server, most of your session beans will be stateful. However, sometimes you may want to use stateless session beans: The bean performs a task that is not tailored to the needs of a particular client. For example, you might use a stateless session bean to fetch from a database a commonly used set of data. The bean doesn't need to hold information about the client across method invocation
55
54 FIRE ……….
56
55 Am Still Alive !!!!
57
56 References On Starters : www.calvinandhobbes.com More on ‘HIS’ Quotes: www.bushisms.com More on EJB: ???????????? Ask Google or Dr. juggy Actually > 1) Text: Mastering EJB by Ed roman 2) www.javaworld.comwww.javaworld.com 3) http://java.sun.com/products/ejb/http://java.sun.com/products/ejb/ 4) http://theserverside.com/home/index.jsphttp://theserverside.com/home/index.jsp
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.