session bean

Upload: s-r-krishnan

Post on 30-May-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Session Bean

    1/31

    What is Session Bean?

    Session is one of the EJBs and it represents a single client inside the Application Server.Stateless session is easy to develop and its efficient. As compare to entity beans sessionbeans require few server resources.

    A session bean is similar to an interactive session and is not shared; it can have only oneclient, in the same way that an interactive session can have only one user. A session beanis not persistent and it is destroyed once the session terminates.

    Session Bean Types

    Session Beans are of two types, Stateful Session Bean and Stateless Session Bean.

    Stateless Session Beans

    A stateless session bean does not maintain a conversational state for the client. When aclient invokes the method of a stateless bean, the bean's instance variables may contain a

    state, but only for the duration of the invocation.

    Because stateless session beans can support multiple clients, they can offer betterscalability for applications that require large numbers of clients. Typically, an applicationrequires fewer stateless session beans than stateful session beans to support the samenumber of clients.

    Stateful Session Beans

    The state of an object consists of the values of its instance variables. In a stateful sessionbean, the instance variables represent the state of a unique client-bean session. Because

    the client interacts ("talks") with its bean, this state is often called the conversationalstate.

    Writing Stateful Session Bean

    A Session Bean is composed of the following parts:

    Remote Interface: The Remote Interface is the client view of the bean.

    Home Interface: The Home Interface contains all the methods for the bean life

    cycle (creation, suppression) used by the client application. Bean Class: The bean implementation class implements the business methods.

    Deployment Descriptor: The deployment descriptor contains the bean

    properties that can be edited at assembly or deployment time.

    Steps involved in developing the Stateful Session Bean can be summarized in followingsteps:

    1. Define Home Interface2. Define Remote Interface3. Develop EJB class

  • 8/14/2019 Session Bean

    2/31

    4. Write deployment descriptors5. Package, deploy and test the application

    Define Home Interface

    The Session bean's home interface defines one or more create(...) methods and each

    create method must be named create and must match one of the ejbCreate methodsdefined in the enterprise Bean class. The return type of a create method is the Bean'sremote interface type.

    In case of Stateless Session Bean there is one create method with no arguments. Aremote home interface extends the javax.ejb.EJBHome interface, while a local home

    interface extends the javax.ejb.EJBLocalHome interface.

    Here is the source code of ourhome interface:

    /*

    * TestSessionBeanHome.java*/package examples;

    /*** Home interface for TestSessionBean.* @author Deepak Kumar* @Web http://www.roseindia.net* @Email [email protected]*/

    public interface TestSessionBeanHome extends javax.ejb.EJBHome{

    public examples.TestSessionBean create() throws javax.ejb.CreateException,java.rmi.RemoteException;

    }

    Define Remote Interface

    As mentioned earlier, Remote Interface is the client view of the bean and the functionsdefined in the remote interface is visible to the client. There should be an implementationin the Bean class for the all the functions defined in the remote interface.

    Here is the source code of ourRemote Interface:

    /** TestSessionBean.java**/

    package examples;

    /*** Remote interface for TestSessionBean.

  • 8/14/2019 Session Bean

    3/31

    * @author Deepak Kumar* @Web http://www.roseindia.net* @Email [email protected]*/

    public interface TestSessionBean

    extends javax.ejb.EJBObject{ /** * The method that returns Hello Message */ public java.lang.String SayHello( ) throws java.rmi.RemoteException;

    }

    Define Enterprise Bean Class

    In the EJB class we write all the business methods along with required that is necessary

    to implement. In the EJB class methods are defined public. The Session Bean interfacemethods that the EJB provider must be defined in the Session bean class are:

    public voidsetSessionContext(SessionContext ic);

    This method is used by the container to pass a reference to the SessionContext tothe bean instance.

    public voidejbRemove();

    This method is invoked by the container when the instance is in the process ofbeing removed by the container.

    public voidejbPassivate();

    This method is invoked by the container when it wants to passivate the instance.

    public voidejbActivate();This method is invoked by the container when the instance has just beenreactivated.

    A stateful session Bean with container-managed transaction demarcation can optionallyalso implements the javax.ejb.SessionSynchronization interface.

    The Session Synchronization interface methods that must be developed are:

    public voidafterBegin();

    This method notifies a session Bean instance that a new transaction has started.

    public voidafterCompletion(boolean committed);This method notifies a session Bean instance that a transaction commit protocolhas completed and tells the instance whether the transaction has been committedor rolled back.

    public voidbeforeCompletion();

    This method notifies a session Bean instance that a transaction is about to becommitted.

  • 8/14/2019 Session Bean

    4/31

    Here is the source code of ourSession Bean class:

    /** SessionBean.java**/

    package examples;

    import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBException;import javax.ejb.SessionBean;import javax.ejb.SessionContext;

    /*** @author Deepak Kumar* @Web http://www.roseindia.net* @Email [email protected]*/

    public class MyTestSessionBean implements SessionBean{

    public voidejbCreate() throws CreateException {

    }

    public voidsetSessionContext( SessionContext aContext ) throws EJBException {

    }

    public voidejbActivate() throws EJBException {

    }

    public voidejbPassivate() throws EJBException {

    }

    public voidejbRemove() throws EJBException {

    }

    /** * The method that returns Hello Message *

    */public String SayHello(){ String msg="Hello! I am Session Bean"; System.out.println(msg); return msg; }

    }

  • 8/14/2019 Session Bean

    5/31

    Writing Deployment Descriptor of Stateless Session

    Bean

    In this section we will write the deployment descriptor for the session bean. We need thedeployment descriptor for application (application.xml), ejb deployment descriptors (ejb-jar.xml and weblogic-ejb-jar.xml) and web.xml files.

    Application Deployment descriptor:

    We need the following application deployment descriptor to create our ear file(example.ear).

    Stateless Session Bean Example

    example.war/example

    example.jar

    EJB Deployment descriptor:

    To create example.jar file we need ejb-jar.xml and weblogic-ejb-jar.xml files. Here is thecode forejb-jar.xml file:

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f271faf5a14710867f386762977775363130961bde50d32e37de68ef70ac9f45cb00376a00a5b4e8680dca787ac19056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f291ba957196d0067e7f77124706e5619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c387177557f1d377ee7f71123e27419056
  • 8/14/2019 Session Bean

    6/31

    EJB ExamplesEJB Examples

    Shopping Cart Session BeanShopping Cart Session Bean

    ShoppingCart

    examples.ShoppingCartHomeexamples.ShoppingCartexamples.ShoppingCartStatefulSessionBeanStatefulContainer

    EJB Test Session BeanEJB Test Session Bean

    TestSessionBean

    examples.TestSessionBeanHome

    examples.TestSessionBean

    examples.TestSessionBeanLocalHome

    examples.TestSessionBeanLocal

    examples.MyTestSessionBean

    Stateless

    Container

    testSessionBean

    java.lang.String

    Test Bean

  • 8/14/2019 Session Bean

    7/31

    EJB Calculator Session Bean

    EJB Calculator Session Bean

    CalculatorBean

    examples.CalculatorBeanHomeexamples.CalculatorBeanexamples.CalculatorBeanLocalHomeexamples.CalculatorBeanLocalexamples.CalculatorSessionBeanStatelessContainer

    CalculatorBeanjava.lang.StringCalculator bean

    Session BeanSession BeanShoppingCart

    *

    ShoppingCart

  • 8/14/2019 Session Bean

    8/31

    *Supports

    The name of our session bean is TestSessionBean, we will call this bean from servlet (asdescribed in the next page).

    The code for weblogic specific ejb deployment descriptor(weblogic-ejb-jar.xml) is asfollows:

    Session Bean ExampleShoppingCart

    ShoppingCart

    TestSessionBean

    TestSessionBeanTestSessionBeanLocal

    CalculatorBean

  • 8/14/2019 Session Bean

    9/31

    CalculatorSessionBeanCalculatorBeanLocal

    The JNDI name for our Staeless Session bean is TestSessionBean. We will use this JNDIname to lookup the Bean and call it from Servlet.

    Web.xml file for war file:

    web.xml file describes the example.war file, which is our web application. Here is thecode of web.xml file:

    sessionTest

    Session Test Servletnet.roseindia.web.servlets.SessionTestServlet

    1

    sessionTest/SessionServlet

    Note that in the above web.xml file we have define a servlet named sessionTest. We willuse this servlet to call the Staleless Session Bean. Here is the code of servlet used to callsession bean:

    /** SessionTestServlet.java

  • 8/14/2019 Session Bean

    10/31

    **/

    package net.roseindia.web.servlets;

    import javax.servlet.*;import

    javax.servlet.http.*;import java.io.*;import javax.naming.*;import javax.rmi.PortableRemoteObject;

    import examples.*;

    /*** @author Deepak Kumar* @Web http://www.roseindia.net* @Email [email protected]* @web.servlet name="sessionTest"* display-name="Session Test Servlet"

    * load-on-startup="1"* @web.servlet-mapping url-pattern="/SessionServlet"*/

    public class SessionTestServlet extends HttpServlet {

    TestSessionBeanHome testSessionBean;

    public voidinit(ServletConfig config) throws ServletException{//Look up home interfacetry {

    InitialContext ctx = new InitialContext(); Object objref = ctx.lookup("TestSessionBean"); testSessionBean = (TestSessionBeanHome)

    PortableRemoteObject.narrow(objref,

    TestSessionBeanHome.class);} catch (Exception NamingException) { NamingException.printStackTrace();}

    }

    public voiddoGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{

    PrintWriter out;response.setContentType("text/html");String title = "EJB Example";out = response.getWriter();

  • 8/14/2019 Session Bean

    11/31

    out.println("");out.println("");out.println("Hello World Servlet!");out.println("");

    out.println("");out.println("

    Servlet

    Calling Session Bean

    ");

    try{TestSessionBean beanRemote;beanRemote = testSessionBean.create();out.println("

    Message from

    Session Bean is: " +

    beanRemote.SayHello() + "

    ");beanRemote.remove();}catch(Exception CreateException){CreateException.printStackTrace();}

    out.println("

    Go to Home

    ");out.println("");out.println("");

    out.close();}

    public voiddestroy() {System.out.println("Destroy");}}

    Deploying and testing Stateless Session Bean

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f201bb3550e64007dfbab7129777053621a3477a8ea5724e76cf89119056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f291ba957196d0067e7f77124706e5619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f300ebe421e64047ae7aa673f776a5563163373a7e01c27e377ec90cd17d8e34aaa1e71b21b55528680dca787ac19056
  • 8/14/2019 Session Bean

    12/31

    In this EJB tutorial we will build, deploy and test the Stateles Session Bean developed inthe last section. We will use ant build tool to build ear file. We will deploy our applicationusing WebLogic console.

    Building ear file using ant build tool

    I am assuming that you have ant build tool installed on your development environment.Download the source code from here and extract in your favorite directory. Opencommand prompt and navigate to the directory /sessionbean/codeand type ant there. Ant build tool will compile, package and create example.ear in the/sessionbean directory. Here is the code of our ant build file:.

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c627e6a4a19056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c627e6a4a19056
  • 8/14/2019 Session Bean

    13/31

  • 8/14/2019 Session Bean

    14/31

    Deploying the Application on Web Logic 6.0 Server

    Run the WebLogic default server:

    To deploy the application we will use WebLogic console. Typehttp://localhost:7001/consoleand enter user name and password to open the WebLogicconsole.

    https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007fef6cff5c6fc3d19056https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007fef6cff5c6fc3d19056https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007fef6cff5c6fc3d19056
  • 8/14/2019 Session Bean

    15/31

    Navigate to "Applications" and then click on "Install a new Application", followingscreen will be displayed:

  • 8/14/2019 Session Bean

    16/31

    Browse "example.ear" and then click on the Upload button. This will upload the file to

    the WebLogic server directory and then install the application.

  • 8/14/2019 Session Bean

    17/31

    Testing the application

    To test the application open browser and type http://localhost:7001/example/index.jsp,following page should be displayed:

    Click on the link "Call Session Test Servlet", it should show you the following output:

    https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007f8e1c0ebd9fc3d9b4c3398c3c86d10ac4619056https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007f8e1c0ebd9fc3d9b4c3398c3c86d10ac4619056
  • 8/14/2019 Session Bean

    18/31

    check the WebLogic server dos console, it should be displaying the message "Hello! I amSession Bean" as show below in the screen shot:

  • 8/14/2019 Session Bean

    19/31

    Writing Calculator Stateless Session Bean

    In this EJB tutorial we will learn how to Write Staleles Session Bean for multiplying thevalues entered by user. We will use ant build tool to build ear file. We will deploy ourapplication using WebLogic console.

    Enterprise Bean remote interface

    All remote interfaces must extend javax.ejb.EJBObject. Remote interface is the clientview of session bean. Methods defined in the remote interface are accessible to the client.

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c206d655f6e0d357eacaa0a3ffb75f919056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f291ba957196d0067e7f77124706e5619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f271faf5a14710867f386762977775363130961bde50d32e37de68ef70ac9f45cb00376a00a5b4e8680dca787ac19056
  • 8/14/2019 Session Bean

    20/31

    In our example we have defined thepublic int multiply(int a, int b)

    method for calling from JSP. Here is code of our Remote Interface:

    package examples;

    /*** Remote interface for CalculatorBean.*/

    public interface CalculatorBean extends javax.ejb.EJBObject{ /** * The method that returns the multiplied value */ public int multiply( int val1,int val2 ) throws java.rmi.RemoteException;

    }

    Enterprise Bean Home interface

    All home interfaces must extend javax.ejb.EJBHome. 'create()' method of homeinterface of the application enables the client to create and remove the session object.

    package examples;

    /*** Home interface for CalculatorBean.*/

    public interface CalculatorBeanHome extends javax.ejb.EJBHome{ public static final String COMP_NAME="java:comp/env/ejb/CalculatorBean"; public static final String JNDI_NAME="CalculatorSessionBean";

    public examples.CalculatorBean create() throws javax.ejb.CreateException,java.rmi.RemoteException;

    }

    Enterprise Bean class

    All Bean class are defined as public and implements the javax.ejb.SessionBean. In thebean class we have implemented the code for

    public int multiply(int a, int b)

  • 8/14/2019 Session Bean

    21/31

    Besides this method other required methods which is to be implemented are:

    1. ejbCreate()2. ejbRemove()3. ejbActivate()

    4. ejbPassivate()5. setSessionContext(SessionContext aContext)

    Here is the code for our Calculator Session Bean:

    /** SessionBean.java**/

    package examples;

    import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBException;import javax.ejb.SessionBean;import javax.ejb.SessionContext;

    /*** @author Deepak Kumar* @Web http://www.roseindia.net* @Email [email protected]*/

    /*** This is the Test Session Bean**/

    public class CalculatorSessionBean implements SessionBean{

    public voidejbCreate() throws CreateException {

    }

    public voidsetSessionContext( SessionContext aContext ) throws EJBException {

    }

    public voidejbActivate() throws EJBException {

    }

    public voidejbPassivate() throws EJBException {

  • 8/14/2019 Session Bean

    22/31

    }

    public voidejbRemove() throws EJBException {

    }

    /** * The method that returns the multiplied value * */public int multiply(int val1, int val2){ System.out.println("I am from multiply : " + val1 + " * " + val2); return val1*val2; }

    }

    Jar Descriptor File

    For creating example.jarejb-jar.xml and weblogic-ejb-jar.xml files are required whichexplains the content of jar file.

    ejb-jar.xml file:

    EJB ExamplesEJB Examples

    Shopping Cart Session BeanShopping Cart Session Bean

    ShoppingCart

    examples.ShoppingCartHomeexamples.ShoppingCartexamples.ShoppingCartStatefulSessionBeanStatefulContainer

  • 8/14/2019 Session Bean

    23/31

    EJB Test Session BeanEJB Test Session Bean

    TestSessionBean

    examples.TestSessionBeanHome

    examples.TestSessionBeanexamples.TestSessionBeanLocalHomeexamples.TestSessionBeanLocalexamples.MyTestSessionBeanStatelessContainer

    testSessionBeanjava.lang.StringTest Bean

    EJB Calculator Session Bean

    EJB Calculator Session Bean

    CalculatorBean

    examples.CalculatorBeanHome

    examples.CalculatorBean

    examples.CalculatorBeanLocalHome

    examples.CalculatorBeanLocal

    examples.CalculatorSessionBean

    StatelessContainer

    CalculatorBean

    java.lang.String

    Calculator bean

    Session BeanSession Bean

  • 8/14/2019 Session Bean

    24/31

    ShoppingCart*

    ShoppingCart*Supports

    Above deployment descriptor defines remote, home and bean class for the bean andassigns a name 'CalculatorBean' to the session bean. Please note that bean of Stateless typeand is defined by:Stateless

    weblogic-ejb-jar.xml file:

    Session Bean Example

    ShoppingCartShoppingCart

    TestSessionBean

    TestSessionBeanTestSessionBeanLocal

    CalculatorBean

  • 8/14/2019 Session Bean

    25/31

    CalculatorSessionBean

    CalculatorBeanLocal

    The WebLogic deployment descriptor assigns jndi name 'CalculatorSessionBean' to the'CalculatorBean' bean.

    Writing JSP and Web/Ear component

    Our JSP file access the session bean and uses it for the calculation and displays the result.

    For this purpose we are using calculator.jsp which displays a form to accept two numbers

    from the user and submits the form data to calculator.jsp. Here is our calculator.jsp:

  • 8/14/2019 Session Bean

    26/31

    Calculator Bean

    CalculatorCalculate *

    Result =

  • 8/14/2019 Session Bean

    27/31

    Web-Component Descriptor File

    For creating war file we need web.xml, which is same as in previous lesson.

    J2EE Enterprise Archive (ear) Descriptor File

    For creating example.earapplication.xml, file is required which explains the content ofenterprise archive, which is same as in previous lesson.

    Building ear file using ant build tool

    I am assuming that you have ant build tool installed on your development environment.Download the source for from here and extract in your favorite directory. Opencommand prompt and navigate to the directory /sessionbean/code

    and type ant there. Ant build tool will compile, package and create example.ear in the/sessionbean directory. Here is the code of our ant build file:.

    Deploying the Application on Web Logic 6.0 Server

    Please refer to previous lesson for deploying the application on WebLogic Server.

    Testing the application

    To test the application open browser and type http://localhost:7001/example/index.jsp,following page should be displayed:

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c627e6a4a19056https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007f8e1c0ebd9fc3d9b4c3398c3c86d10ac4619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f301fac4512670f6bf1b86c627e6a4a19056https://www.vtunnel.com/index.php/1010110A/953077409dc9fad769b6d95897ff7c5a6ec40007f8e1c0ebd9fc3d9b4c3398c3c86d10ac4619056
  • 8/14/2019 Session Bean

    28/31

    Click on the link "Calculator Links", it should display the form to enter the two values:

    Click on the Calculate button to view the result. Following should be displayed:

  • 8/14/2019 Session Bean

    29/31

    Understanding Stateful and Stateless Session Bean Life

    Cycle

    In this section of EJB tutorial, we will learn about the lifecycle of Stateful and StatelessSession Beans.

    Stateless Session Bean Life cycle

    There are two stages in the Lifecycle of Stateless Session Bean. These are:

    a) Does Not Exist

    In the Does Not Exist stage, bean does not have instance in the memory. In this stagebean has not been instantiated.

    b) Method Ready PoolIn the Method Ready Pool stage bean has instance(s) in the memory of the EJB containerand it is ready to serve clients. On the startup of the EJB container some instances of thebean are created and placed in the pool. EJB container creates the new instance of theBean and then sets the session context (setSessioncontext()) and it calls the ejbCreate()

    https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f291ba957196d0067e7f77124706e5619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f291ba957196d0067e7f77124706e5619056https://www.vtunnel.com/index.php/1010110A/953077409dd2e2c326a8de4481e2280937951f46f8ed8eecc8e639d6403c92d59f201bb3550e64007dfbab7129777053621a3477a8ea5724e76cf89119056
  • 8/14/2019 Session Bean

    30/31

    method to place the bean in the Method Ready Pool stage. Container calls theejbRemove() method to move the bean into Does Not Exist state.

    Following Diagram shows the Life cycle of Stateless Session Bean

    Stateful Session Bean Life cycle

    There are there stages in the life cycle of Stateful Session bean Life cycle. These are:

    a) Does Not ExistThis is the Does Not Exist stage, bean does not have instance in the memory. In this stagebean has not been instantiated.

    b) Method Ready PoolIn the Method Ready Pool stage bean has instance in the memory of the EJB containerand it is ready to serve client. One instance of the Stateful Session Bean servers only oneclient. When Client Calls create(args) method on the Home Interface, server creates newinstance of the bean and sets the Session Context and then container calls theejbCreate(args) method on the bean and places the bean into Method Ready Pool stage.ejbRemove or Timeout moves the bean into Does Not Exist stage.

    c) Passive stateIn the Passive state the bean is passivated to conserve the resource. The passivate methodis called before the instance enters the "passive" state. The instance should release any

    resources that it can re-acquire later in the ejbActivate() method. After the passivatemethod completes, the instance must be in a state that allows the container to use the JavaSerialization protocol to externalize and store away the instance's state. ejbRemove orTimeout moves the bean into Does Not Exist stage.

    Following Diagram shows the Life cycle of Statelful Session Bean

  • 8/14/2019 Session Bean

    31/31