• No results found

Stateless Session Beans

N/A
N/A
Protected

Academic year: 2022

Share "Stateless Session Beans"

Copied!
55
0
0

Loading.... (view fulltext now)

Full text

(1)

Session Beans

Session Beans

Stateless Session Beans

Stateful Session Beans

(2)

Review

• Enterprise Java Beans

– J2EE/JavaEE Architecture – Logical Architecture

– EJB Container (Transaction, Security, Persistent, Management, …) – Objects: Session Beans (Stateless, Stateful), Entity Beans (BMP,

CMP), Message Driven Beans

– Components: Component interface (Remote interface, Local interface), Home interface (Home interface, Local Home interface), Bean class, EJB deployment descriptors, server deployment descriptor, DB mapping descriptors, …

– Implementation

• JNDI

– API, SPI, Naming Manager

– Context Factory, Initial Context Factory

(3)

Objectives

• Session Beans

– Definition

– Conversation & Non-conversation – Call back methods

– Deployment Descriptor structure

• Stateless Session Beans

– Definition – Life Cycle

– Implementation

– Enterprise Application Development Process

• Stateful Session Beans

– Definition – Life Cycle

– Enterprise Application Development Process

(4)

Session Beans

Definition

• A kind of enterprise beans that represent business processes (any task with logic, workflow, and algorithms).

• Perform business functions for the clients inside the application server

– Represents business process without having persistent storage mechanism – Not permanent in Nature

• Are reusable Java components

– They model a specific user task such as entering product details or implementing a process that maintains a conversation state with the client application

– Works on behalf of the client code that is invoking it

• Two main aspects of lifetime of a Session bean are

– The instances of Session bean are not shareable between multiple clients (only one client can deal with that particular session bean)

– Life cycle of a Session bean’s instance is controlled by the container and the instance is removed by the container when timeout occurs

• Deployed (run) in either a stand-alone EJB container or EJB containers that are part of Java Enterprise Edition (Java EE) application servers

(5)

Session Beans

Need for Session Beans

• Helps to develop a robust and feature-rich business logic tier

• Features of Session beans are

– Concurrency and Thread Safety

• The enterprise application can be shared by multiple clients remotely at the same time because the session are designed to handle multiple client requests

– Remoting and Web Services

• Supports remote access invocation through RMI and SOAP- based

– Transaction and Security Management

• Supports transactions, authorizations, and authentication

(6)

Session Beans

Features

• Life Cycle

– A session bean may last as long as the client session.

– Will not survive if the application server changes or crashes.

– They are objects which are present in-memory which die along with the surrounding environment and are not persisted in a database.

• Types

– Stateless Session Bean – Stateful Session Bean

• Session bean class is implemented including

– From javax.ejb.Session Bean – Callback methods

• All the methods are used by the application that uses them to gain control over the different stages of the beans life cycle

• Can be invoked on the bean by the container

– Business methods

• Declared in the business interface and the implementing bean class should match in terms of method name and method signature

(7)

Session Beans

Conversation & Non-Conversation

• Conversation

– Can be defined as the period between the client accessing a Session bean instance and client invoking the remote method on the instance

– Define as an interaction between a client and a bean.

– Is composed of a number of method calls between them

– Stretches across a business process with respect to the client.

– Stateful session beans can retain their conversational state.

– Ex: Shopping Cart

• Non-Conversation

– Clear of all previous information (same as the HTTP protocol)

– A stateless session bean conducts a conversation that spreads over a single method call.

• State of the instances of Session bean cannot be saved in a DB or a file system.

– Session beans are not persistent but they can perform DB operations

(8)

Session Beans

CallBack Methods

• public void setSessionContext(SessionContext ctx)

• public void ejbCreate([args])

• public void ejbPassivate()

• public void ejbActivate()

• public void ejbRemove()

(9)

Session Beans

EJB Session Context

• Contains information about bean’s status such as reference of bean home interface, client’s security permissions and transactions currently associated with the bean instance.

• The EJB session context object enables session beans to interact with EJB container to perform the following functions:

– Retrieve the reference to the home objects – Retrieve transaction attributes

– Set transaction attributes

• javax.ejb.SessionContext interface

– setSessionContext()

Container

setSessionContext() Bean

Session Context (Gateway)

Associate

(10)

Session Beans

EJB Session Context

public class theBean implements SessionBean {

private SessionContext ctx;

public void setSessionContext(SessionContext ctx) {

this.ctx=ctx;

}

. . . }

(11)

Session Beans

ejbCreate

• Initialize the bean

• Can be defined many times, and each time it takes various args (applying to stateful)

• Is invoked when the client side call the create method

public class theBean implements SessionBean { . . . .

public void ejbCreate() {

}

. . . }

public class theBean implements SessionBean { . . . .

public void ejbCreate(String sName, String sPass)throws CreateException {

}

. . . }

(12)

Session Beans

ejbPassivate & ejbActivate

• ejbPassivate:

– The EJB container will passivate some beans by writing them to a temporary storage when there are too many beans that have been instantiated.

– The container release the bean (resource).

– This method is called just before the bean is passivated, then all resources that the bean has will be released.

• ejbActivate:

– Client may to use a particular bean, which has been passivated.

– The Container call the ejbActivate to activate the bean into memory and the bean’s implementation will require all resources necessary.

• Notes: stateless beans are not passivated because them have no state and can be created and destroyed.

public class theBean implements SessionBean { . . . .

public void ejbPassivate() {…}

public void ejbActivate() {…}

. . . }

(13)

Session Beans

ejbRemove & Business methods

• ejbRemove:

– The ejbRemove() method is called when the instance of the bean is about to be destroyed or container decides that the life cycle of bean has expired (all the resources associated with bean have to be released).

– It is a clean-up process and is required for all the bean.

– This method does not accept any parameters and can be used for a single bean.

– Notes: The container may not call the ejbRemove because of a container crash, or the occurrence of a critical exception.

• Business Method:

– Business methods are written to solve business logic problems.

– Business methods are contained in the remote/local interface of the bean for the client/application to access them.

– Declared in the business interface and the implementing bean class should match in terms of method name and method signature

(14)

Session Beans

ejb-jar.xml Structure

<?xml version="1.0"?>

<ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">

<enterprise-beans>

<session>

<ejb-name>Representation Name</ejb-name>

<home>[package.]Home Interface class</home>

<remote>[package.]Remote Interface class</remote>

<ejb-class>[package.]Bean Class</ejb-class>

[<local-home>[package.]Local Home interface class</local-home>]

[<local>[package.]Local interface class</local>]

<session-type>Stateless/Stateful</session-type>

<transaction-type>Bean/Container</transaction-type>

</session>

</enterprise-beans>

</ejb-jar>

(15)

Session Beans

jboss.xml Structure

• Provides the container information about the JNDI mapping, persistence information and database mapping.

<?xml version="1.0"?>

<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 4.0//EN"

"http://www.jboss.org/j2ee/dtd/jboss_4_0.dtd">

<jboss>

<enterprise-beans>

<session>

<ejb-name>Representation name</ejb-name>

<jndi-name>name reference to home</jndi-name>

<local-jndi-name>name reference to local home</local-jndi- name>

</session>

</enterprise-beans>

</jboss>

(16)

Session Beans

The Client Side

• It acquires a JNDI initial context and the naming context.

• Home object is located using JNDI.

• Client requests the Home Object creating the EJB Objects

• Client calls methods on the bean using the EJB Object.

• Conversations are created using home interface and used from the client code

• Deployment descriptors limit the pool size.

• Lastly, the EJB objects are removed.

(17)

Stateless Session Beans

Definition

• Is used for a single request conversation

• Executes Business operations without maintaining the client state

– It does not maintain any conversational state with the client and therefore it does not require activation or passivation (non-conversation)

– Invocation of each method is independent of the earlier method invocation

– The client has to pass on all the information necessary for the bean through the parameters for the business method.

– Completes the functionality of the business logic in one method invocation – Any instances of any Stateless Session bean can service any client

• Lightweight Component – Doesn’t contains complex data structure

– Not having instance variables to store information

– Can’t used when information need to be used various method calls

• Efficient – Same Session Bean instance can handle multiple client requests

– The Session Beans can be pooled and reused

• Improves the scalability of an application

(18)

Stateless Session Beans

Life Cycle

• Life cycle

– Bean Creation: Stateless are created by the container and added to a bean pool.

– Bean Use: Stateless are used when the clients call their business methods.

– Bean Removal: Stateless are removed when the EJB container decides there are too many beans in the pool or the beans throw a system exception.

• The Session Beans may have a timeout period

– If a bean instance is not used within the specified time, the bean instance is destroyed

– The client can destroy the bean instance by call the remove method on the client side to the container invoking the ejbRemove method

(19)

Stateless Session Beans

Life Cycle

Start

(Does not exist)

Instances (Ready)

ejbRemove() ejbCreate()

init instance setSessionContext()

Client called remove() (or the client times out) Client invoke method

(20)

Stateless Session Beans

Life Cycle

• The container activities apply to stateless session bean life cycle

– Uses default constructor to create a bean instance – Injects resources such as DB connections

– Put instance in a managed pool

– Receives request from client and pulls a bean instance from the pool

– Executes the business method invoked by the client using the business interface which contain the bean instance reference

– Pushes the bean instance into the pool once the execution of the method is over

– Destroys the bean instance

(21)

Stateless Session Beans

Life Cycle

• The container activities apply to stateless session bean life cycle

– Uses default constructor to create a bean instance – Injects resources such as DB connections

– Put instance in a managed pool

– Receives request from client and pulls a bean instance from the pool

– Executes the business method invoked by the client using the business interface which contain the bean instance reference

– Pushes the bean instance into the pool once the execution of the method is over

– Destroys the bean instance

(22)

Stateless Session Beans

Rules for Session Beans

• Should have at least one business interface

• Should not declare the class as final or abstract

• With bean class

– implements javax.ejb.SessionBean

– Should implement a no argument constructor because it is invoked when an instance of the Session bean is created

– Must define business with public keyword and life cycle callback methods with ejb prefix

• With stateless session bean, the bean class must

– Not declare any properties or attributes

– The ejbCreate method not containing any parameters

(23)

Stateless Session Beans

Implementations

• Step 1: Create Remote Interface

– extends javax.ejb.EJBObject – Define business method

– Class interface & business methods must declare public.

– Those methods must throws java.rmi.RemoteException

• Step 2: Create Home Interface

– extends javax.ejb.EJBHome

– Define create() without parameter and throws java.rmi.RemoteException and javax.ejb.CreateException

– The create()’s return datatype is Remote Interface Class – Class Interface & methods must declare public.

(24)

Stateless Session Beans

Implementations

• Step 3: Create Local Interface (Optional)

– extends javax.ejb.EJBLocalObject

– Define the methods same or not as Remote Interface without throws java.rmi.RemoteException (each of method)

– The interface class & methods must declare public.

• Step 4: Create Local Home Interface (Optional)

– extends javax.ejb.EJBLocalHome

– Define the create() with javax.ejb.CreateException (not java.rmi.RemoteException)

– The create()’s return datatype is Local Interface Class

– The interface class & methods must declare public.

(25)

Stateless Session Beans

Implementations

• Step 5: Create Bean Class

– implements javax.ejb.SessionBean – implements 05 callback methods

– implements all of methods which defined in Remote/ Local Interface (declare public)

– This class must declare public.

– Exceptions and parameters in bean class are same as the class interface except RemoteException

• Step 6: Create Deployment Descriptor with ejb-jar.xml & jboss.xml (deploy on JBoss – Application Server) which put in META-INF directory.

– specifies how the container is supposed to create and manage the enterprise bean object.

– defines the name of the enterprise bean class, and the names of the home and remote interfaces.

– ejb-jar file provides naming information about enterprise bean, remote interface and home interface.

(26)

Stateless Session Beans

Implementations

• Step 7: make jar file

– Compile Java classes – Usage command:

jar –cvf filename.jar java-Classes META-INF/*

• Step 8: Deploy

– Running the Application Server

– Deploy EJB-JAR file on Application Server

(JBOSS_HOME/server/default/deploy – get name reference)

• Step 9: Create Client program

– Use JNDI to lookup Home Object on Application Server – Instantiate EJB Object

– Invoke methods necessary.

• Step 10: Running the Client

(27)

Stateless Session Beans

Enterprise Application Development Process

• Step 1: Creating a new Enterprise Application project (EJB and Web Client – ear file)

• Step 2: Creating the new corresponding bean depending on your purpose.

• Step 3: Building/ Modifying the business/callback methods on Beans

• Step 4: Mapping the JNDI to beans

• Step 5: Creating the GUI to consumes EJB on web modules

• Step 6: Building and Deploying Enterprise application on Application Server

• Step 7: Executing the Enterprise Application

(28)

Stateless Session Beans

Creating

• Click Next Button.

• Then type the Project Name, then click Next button

(29)

Stateless Session Beans

Creating

• Click Next Button.

Fill your project name

(30)

Stateless Session Beans

Creating

Choose the Jboss 4.2.3 Choose J2EE 1.4

Don’t change anything that is default by tools

Click Finish Button

(31)

Stateless Session Beans

Creating

(32)

Stateless Session Beans

Next Steps

• Step 2: Creating the new corresponding bean

• Step 3: Building/ Modifying the business/callback methods on Beans

• Step 4: Mapping the JNDI to beans

Creating stateless bean as whole steps in

previous tutorials in EJB Development

process on the Xxx-ejb module

(33)

Stateless Session Beans

Creating GUI with Web Page and consumes

• Creating the GUI application

• Creating the Servlet to process and consume the EJB

– Creating the reference to the EJB on the coding by right click on code – Then choose Insert Code, click Call Enterprise Bean …

(34)

Stateless Session Beans

Creating GUI with Web Page and consumes

Choose the appropriate bean

Modify the Reference Name, then choose the scope reference of the Bean

Click Ok Button

Modify the Reference Name that is named in jboss.xml at <[local-]jndi-name> tag

(35)

Stateless Session Beans

Creating GUI with Web Page and consumes

(36)

Stateless Session Beans

Creating GUI with Web Page and consumes

• Modifying the code in servlet as following

(37)

Stateless Session Beans

Building, Deploying, and Executing

(38)

Stateless Session Beans

Building, Deploying, and Executing

(39)

Stateful Session Beans

Definition

• Is used for business processes that span multiple method request or transactions have to be serviced

• Maintains the State of a client.

– It retains the data pertaining to a specific client between method invocations and can be maintained from one method invocation to the other

• The conversional state must be stored in the bean

– Stores client state in instance variable

• Cannot be swapped between EJB objects nor can be kept in a session pool

– Once a stateful is assigned to an EJB object, it is available to that object for its entire life cycle

– Pooling has to be done to conserve resources and enhances scalability.

• The container swaps out a bean and saves the conversational state to the hard disk or other storage devices. This process is called passivation.

– The beans are not persistent. It can access data in DB but does not represent DB’s data

• To passivate a bean a container uses LRU method.

(40)

Stateful Session Beans

Definition

• When the client requests for a method, the passivated conversational state is returned to the bean. The bean is again ready to meet the request. This process is called activation.

• To activate a bean a container uses Just-in-Time (JIT) method.

• Can used when information need to be used various methods calls

• Stateful bean instance can service the requests of a single client only

• Reduces application scalability

Storage

Convert to

Release resource of chosen Bean → Memory freed Bit - blob

Conversational state of a bean

Written to storage in case of

passivation

Read from storage into the memory in case of activation Convert into data

from bit - blob

(41)

Stateful Session Beans

ejbPassivate

Client

ObjectEJB

Other Enterprise

beans

Storage

Invoke business methods

Convert - Marshalling

The EJB Container/Server

Take the LRU Bean Call ejbPassivate() HomeEJB

Conversation State

Bit – blob

Store passivated bean state

Serializethe bean state

Enterprise Bean

(42)

Stateful Session Beans

ejbActivate

Storage

Client EJB Container/Server

Reconstruct bean Call ejbActivate()

invoke business method

Invoke business methods

Find converstation state of bean which stored EJB

Object

Other Enterprise

beans HomeEJB

Bit –

blob Retrieve the passivated state of bean

Convert -

Unmarshalling

Enterprise Bean

(43)

Stateful Session Beans

Life Cycle

• Bean Creation: Statelful are created by the container when a client makes a request for a bean.

• Bean Use: Statelful are used when the clients call their business methods.

• Bean Passivation: Statelful are passivated or made inactive when the client does not call the session bean business methods for a specified period of time.

• Bean Activation: from passivation, the Stateful moves to activation stage when the client request for bean services after a prolonged period of inactivity.

• Bean Removal: beans are removed when the container decides there are too many beans in the pool or the beans throw a system exception.

Start (not exist)

Instances – ready

ejbRemove() ejbCreate(arg)

init instance setSessionContext()

Client called remove() (or the client times out) Client invoke method

Passivate ejbPassivate()

ejbActivate()

Client need more resrc

Client called method on passivate

(44)

Stateful Session Beans

Life Cycle

• Stateful does not use instance pooling

• The instances are dedicated to one client for entire application

• The bean instances are removed from the memory when they are not in use

• EJB object remains connected with the client

• Bean instances are passivated before it is removed from the memory and when the EJB object becomes active the instance is activated to restore its state

• Mechanism of container on stateful

– Uses the default constructor to create the bean instance – Injects the resource such as DB connections

– Stores the bean instance in the memory

– Executes the business method invoked by the client – Waits and executes further requests

– Passivates the bean instance when the client is idle

– Activates the bean instance on receiving a call from the client

– Destroys a bean instance when the bean is not invoked for period time

– Requests for removal of bean instance from the client requires the activation of the bean instance followed by destruction

(45)

Stateful Session Beans

Implementation

• Build the application same as stateless session bean

• The create method of Stateful Bean should be passed parameter(s). (optional)

• Adjust element <session-type> value from stateless to stateful in ejb-jar.xml file

• Make jar file, Deploy, and code client to testing (is same as stateless session bean)

• Ex

– Write program to count up one by one when the client

request.

(46)

Stateful Session Beans

Example

• To create one more create method in Bean, click right mouse on the bean code, then choose Insert code, click Add Create Method …

(47)

Stateful Session Beans

Example

(48)

Stateful Session Beans

Example

(49)

Stateful Session Beans

Example

(50)

Stateful Session Beans

Example

(51)

Session Beans

Stateless vs. Stateful

Stateless Stateful

Advantages:

- Pooling is simple in stateless session bean as there is reuse of beans and this reduces overload

- Loss of conversations is comparatively less in a stateless session bean (non – conversation)

- Pooling uses swap bean with activation

& passivation processes (in storage) when clients request.

- Conversation with the client maybe lost as there is caching of client conversation each time a bean is used.

(disadvantages) DisAdvantages:

- Client-specific data needs to be given for every method invocation

-Bandwidth could be reduced for other processes, as data has to be passed each time

-Input/Output bottlenecks are more in stateless session beans

- Data is not pushed to the bean for every method invocation (advantage) - Bean state has to be activated and passivated in between method invocations. Therefore there can be I/O bottlenecks.

(52)

Session Beans

Practices used for writing Stateful

• Always try to keep the conversations short.

• Try to use an EJB product that persists stateful conversations.

• Always write client code that takes into account bean failures.

• The decision to choose stateless or stateful depends on EJB deployment, and the use of transaction.

• Notes: The stateful can not be pooled because conversation

must be stored in bean (client need this in next request)

(53)

Session Beans

Exercises

• Building the Enterprise application applying the three tiers model can do following tasks

• The Application Server provides the shopping cart methods that allow view, insert to, and remove the cart

• The Web Server provides the useful GUI for uses choose and remove book from cart

• The client can use the Web Browser to use this application

• Besides, the user can order the selected items/ products

to the store or company, that are stored in DB

(54)

Summary

• Session Beans

• Stateless Session Beans

• Stateful Session Beans

Q&A

(55)

Next Lecture

• Entity Beans

– Definition, Life cycles – Call back method

• Bean Managed Persistence – BMP

– Implementation

References

Related documents

Stöden omfattar statliga lån och kreditgarantier; anstånd med skatter och avgifter; tillfälligt sänkta arbetsgivaravgifter under pandemins första fas; ökat statligt ansvar

Byggstarten i maj 2020 av Lalandia och 440 nya fritidshus i Søndervig är således resultatet av 14 års ansträngningar från en lång rad lokala och nationella aktörer och ett

Omvendt er projektet ikke blevet forsinket af klager mv., som det potentielt kunne have været, fordi det danske plan- og reguleringssystem er indrettet til at afværge

I Team Finlands nätverksliknande struktur betonas strävan till samarbete mellan den nationella och lokala nivån och sektorexpertis för att locka investeringar till Finland.. För

Generally, a transition from primary raw materials to recycled materials, along with a change to renewable energy, are the most important actions to reduce greenhouse gas emissions

I två av projektets delstudier har Tillväxtanalys studerat närmare hur väl det svenska regel- verket står sig i en internationell jämförelse, dels när det gäller att

Generella styrmedel kan ha varit mindre verksamma än man har trott De generella styrmedlen, till skillnad från de specifika styrmedlen, har kommit att användas i större

Quoting marketing professor Theodore Levitt, that people do not buy “quarter-inch drills but quarter-inch holes”, Grönroos emphasises that “customers do not look for goods or