Presentation is loading. Please wait.

Presentation is loading. Please wait.

DEVELOPING ENTERPRISE APPLICATIONS USING EJB

Similar presentations


Presentation on theme: "DEVELOPING ENTERPRISE APPLICATIONS USING EJB"— Presentation transcript:

1 DEVELOPING ENTERPRISE APPLICATIONS USING EJB
SESSION BEAN

2 CONTENTS Enterprise Java Beans JNDI Logical Architecture of EJB
Session Beans EJB Development Process Enterprise Application Development Process Workshops Exercises

3 COMPONENT ARCHITECTURE
Components are building blocks of an application Provides a set of services or functions, such that it can easily interact with other applications or components Consists mainly of Web components (JSP, Servlet, …), Business components (EJB), and Service components (Mail, JDBC, JMS …). Flexible, Portability and Reusable An enterprise application is usually composed of a three-layer architecture Presentation Layer (Web Component, GUI Component, Client console) Business Layer (Business Component) Business logic Comprises business rules or methods using which specific business functions can be managed Refers to the workflow or the ordered task of passing data from one software sub-system to another Business objects Are the set of objects and the relationships between them Encapsulate both the data & business behavior associated with the entity that it represents Have the required features: reusability, access control, remote access, multi-user, highly available, state maintenance, transactional, and shared data Data Layer Access control: phan quyen su dung

4 DISTRIBUTED OBJECT ARCHITECTURE
Web Application Server Request DB Response

5 EVOLUTION of EJB Building application software is complexity
The software can process multi-data The software is available online. The developer worries about the security, transaction, scalability, concurrency, resource management, persistent, error handling, and many more system level problems. Software assurance and performance are affected because the developer can not concentrate fully on the developing the business logic (from implementation logic). EJB was developed so that it would: Specialize in handling the business logic of an application Be robust Be secure so that it cannot be tampered. EJB provides a component to create middleware which is deployed on Application Server (3 tiers architecture). EJB Component has been designed to encapsulate business logic. Robust: thiet thuc, manh me, chac chan Temper: ep lai, co lai – giam tinh nang

6 EJB Released by Sun Microsystems in 1998
EJB is a server-side component that simplifies the process of building enterprise-level & distributed applications in java Write-once, run-anywhere, middle-tier components which consists of methods that implements the business logic EJBs are interprocess components and Java Beans are intraprocess components There are two more ways of looking at EJBs EJBs are specification: lay out rules and standards on how you should code your EJBs. EJBs are Java interfaces: EJBs are code by the extending/implementing the EJB interfaces available in the J2EE package Interprocess: lien tien trinh Intraprocess: noi xu ly

7 EJB (cont) Characteristics Types
Hides server-side system level issues from developers. Defines a standard component architecture that enables you to build distributed object-oriented business applications. Facilitates creating enterprise-level applications by allowing easy integrating with other EJB components as well as with other components, such as servlets, Java Server Pages (JSP), and Java Beans. Enables you to create components and applications that are reusable across various J2EE-compliant servers Types Session Bean – Represents business process without having persistent storage mechanism Stateless Session Bean Stateful Session Bean Entity Bean – Persists across multiple sessions and multiple clients & Having persistence storage mechanism Bean-managed Persistence [BMP] Container-managed Persistence [CMP] Message-driven Bean – Asynchronous messaging between components of EJB.

8 EJB IN J2EE ARCHITECTURE

9 APPLICATION/EJB SERVER
Provides many services Network connectivity to the container Instance Passivation – Temporarily swap out a bean from memory storage Instance Pooling – Multiple clients share same instance Database Connection Pooling – Contains a set of database connection Precached Instances – Maintains cache, which contains information about the state of the EJB Other services Runtime Environment Support the containers interaction Process and Thread Management Receive and process requests System Resource Management Feasible: thuan tien, tien loi

10 EJB CONTAINER Acts as an interface between an enterprise bean and client Provides following services Security Transaction Management Persistence Life Cycle management Remote Client Connectivity Responsible for providing several APIs J2SE API EJB Standard Extension JDBC Standard Extension JNDI Standard Extension JMS Standard Extension JavaMail Standard Extension (for Sending mail only) JAXP (Java API for XML Processing) JTA Standard Extension (Only UserTransaction interface) Spawn: de trung, tao ra

11 JAVA NAMING and DIRECTORY INTERFACE
A naming service (which has its own set of rules for creating valid names) allows you finding an object in a system based on the name associated with the object which is called “binding”. A directory service is an extension of a naming service (an object is also associated with a name, which can be look up, and allowed to have attributes) Java Naming and Directory Interface (JNDI) is a specification for accessing naming and directory services Java Naming and Directory Interface provides the naming and directory functionality to Java applications. Provides a standard interface to locate the components, users, networks, and services placed across the network. Bridges the gap between directory services and makes it possible for the developer to write portable naming and directory services JNDI abstracts the code from a dicretory service and allows the user to plug in a different directory services. (without changing the service code) JNDI provides javax.naming.* interface JNDI separate two parts JNDI API JNDI SPI Naming Concepts of JNDI Atomic: It’s a simple and basic name. Ex: Windows Compound: the collection of one or more atomic names. Ex: C:\Windows\System32 Composite: A name has multiple naming system. Ex̣:

12 JNDI ARCHITECTURE Java Application
Accessor Naming Directory services through APIs JNDI API NAMING MANAGER allows Naming and Directory vendors can plugin transparency JNDI SPI DNS RMI CORBA LDAP LDAP: Lightweight Directory Access Protocol

13 INITIAL CONTEXT FACTORY
Naming System Binding Initial Context Factory is the point where all naming and directory operations are first performed. When the initial context is acquired, all information pertaining to this must be provided to JNDI. The internal storage of JNDI emulates tree data structure. Each InitialContext acts like an internal node and each reference to the resources acts like the leaves The directory context or directory object is another type of context. It is used to define methods for inspecting and modifying attributes associated with a directory object. Acquire = obtain, get Pertain: dua toi, gan den

14 <Biến context>.lookup(tên đối tượng)
JNDI API & LIBRARIES The Context is represented by the javax.naming.Context interface that has the necessary methods to put objects into the naming service, and also to locate them. The starting point is called an InitialContext, represented by javax.naming.InitialContext interface The references in JNDI are represented by javax.naming.Reference interface The lookup() method retrieves the object bound to the name and throws a javax.naming.NamingException, if a naming exception is encountered <Biến context>.lookup(tên đối tượng) The remote calls in EJB make use of RMI-IIOP (Remote Method Invocation-Internet Inter-Orb Protocol) which does not support explicit casting of the EJB object obtained from the remote object to a local object. Instead, Java a RMI-IIOP provides a mechanism to narrow the Object you have received from your lookup to the appropriate type by using the javax.rmi.PortableRemoteObject class & its narrow() method The method narrow() of which parameters narrowFrom is the object that has to be narrowed and narrowTo is the desired type. It returns the object which is cast to the desired type and throws ClassCastException, if narrowFrom cannot be cast to narrowTo The supported files are jndi.jar, fscontext.jar, providerutil.jar

15 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider Provide the components to solve business problem (that are packaged them to the ejb-jar file Reusable components Assemble other components into application. Distribution

16 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider App Assembler Create EJB For Assembling different EJB Components in order to build a complete application Analyzing a business problem and assembling EJB components accordingly to solve the problem Building new EJB components Writing the integration code required to associate the EJB components build by different bean providers

17 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider App Assembler Deployer Create EJB Assemble components Customizing enterprise bean Accumulate information about operational requirements such as security, hardware, and transaction before deploying the bean For deploying an assembled application in an application server

18 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider App Assembler Deployer Create EJB Assemble components Providing the deployment tools that are required by the deployer for deploying EJB components Providing run-time support for beans that are deployed on EJB Server Container Provider

19 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider App Assembler Deployer Create EJB Assemble components For providing EJB Server, which manages client access to an application in a distributed environment For managing transactions and distributed objects Provide Container Container Provider Server Provider Apply

20 PARTIES INVOLVED in EJB DEPLOYMENT
Bean provider App Assembler Deployer Systems Administrator Create EJB Assemble components Deploy components Managing and running an EJB application Configuring and managing the network infrastructure of an EJB application Provide Container Container Provider Server Provider Managing the working of EJB server and EJB container Apply Monitoring the working of deployed EJB applications

21 LOGICAL ARCHITECTURE of EJB
EJB container/ server Create Home Obj Instance EJB Context (Local) Home Object Client EJB Obj Reference Create instance Bean create DB Invoke Methods Send invoke connect EJB Object Enterprise Bean JNDI Retrieve data Lookup Naming Services 03 tiers Architecture

22 COMPONENTS OF EJB Components of an enterprise bean The Remote
interface The Local Interface The Home Interface The LocalHome Interface The EJB object The Home object The EJB-jar file Deployment Descriptors The bean class

23 EJB OBJECT EJB Container/Server (substitute object)Proxy
The container is the middleman between the client and the bean. It manifests itself as a single network-aware object. This network-aware object is called the EJB Object EJB Container/Server Transaction Security EJB Obj Client Delegates Method Instance Bean Request/ Call/ invoke method Manifest: hien thi, chung to Delegate: giao thac, uy nhiem Return values Pools (substitute object)Proxy ..... Bean configuration to use Management Session JNDI registry ... 23

24 EJB OBJECT (con’t) Interface javax.ejb.EJBObject
Methods Descriptions getEJBHome() Retrieves the reference to the corresponding Home Object getPrimaryKey() Return the PrimaryKey for EJB Object (Entity Bean) remove() Destroy EJB Object (delete the bean from the underlying persistent store, means delete a record on DB – Entity Bean) getHandle() Obtain the handle (is a persistent reference to the EJB Object) for the EJB Object isIdentical() Checks whether two EJB Objects are similar Relationship between Java RMI and EJB Objects public interface javax.ejb.EJBObject extends java.rmi.Remote (The physical location of remote object is hidden from the Client RMI) Can be called from a different JVM Offers Location Transparency (Portability of Client Code)

25 REMOTE INTERFACE define perform Remote Interface
Functionality of Implementing in instance bean Business methods define perform Remote Interface extends java.ejb.EJBObject public interface Welcome { } extends javax.ejb.EJBObject public String welcome() ... throws java.rmi.RemoteException; Note: System level operations such as persistence, security and concurrency are not included in remote interface.

26 LOCAL INTERFACE EJB 2.0 can expose their methods to clients through new Local Interface Standard Java interface which allows the beans to expose its methods to other bean reside within the same container (local clients) Eleminate the overhead of the remote method call (java.rmi.RemoteException) Use pass by reference semantics (speed up in processing and efficiency) Not inherit from RMI (extends javax.ejb.EJBLocalObject) public interface WelcomeLocal extends javax.ejb.EJBLocalObject { public String welcome(); ... } EJB Container/ Server Session Bean Other Beans Invokes Methods exposes Local Clients

27 HOME OBJECT EJB Container/Server
Create new EJB Object Client EJB Home return Object Create EJB Object Instance Bean Return EJB Obj location EJB Obj Client code will request for an object from the EJB Object Factory, which know as the home object (instantiates EJB Object) Responsibilities Create (Instantiate) EJB Objects Initial information for EJB Object s Find or search for existing EJB Objects(Entity Bean) Remove EJB Objects (deletes the bean from the underlying persistent store) Select EJB Objects (Entity Bean)

28 HOME OBJECT (con’t) Interface javax.ejb.EJBHome (extends java.rmi.Remote) Methods Descriptions getEJBMetaData() Retrieve information about EJB (Beans’ information) that are being worked on. The information received is encapsulated in the EJBMetaData object, which returns the method. remove() Destroy EJB Object following - Passing the javax.ejb.Handle object, which remove EJB Object that is based on the already retrieved EJB Handle - Passing a primary key to remove beans (one record) from the underlying persistent store.

29 HOME INTERFACE Home Interface public interface WelcomeHome { }
Create EJB Object Initialize Home Interface extends java.ejb.EJBHome Find, Select Destroy public interface WelcomeHome { } extends java.ejb.EJBHome public Welcome create() public Welcome findByPrimaryKey() ...; ... throws java.rmi.RemoteException;

30 LOCAL HOME INTERFACE Standard Java interface which allows the beans to expose its methods to other bean reside within the same container (local clients) Eleminate the overhead of the remote method call (java.rmi.RemoteException) Use pass by reference semantics (speed up in processing and efficiency) extends javax.ejb.EJBLocalHome Notes: LocalObject is used as Return Values public interface WelcomeLocalHome extends javax.ejb.EJBLocalHome { public WelcomeLocal create(); public WelcomeLocal findByPrimaryKey(); ... }

31 Well-defined interface
BEAN CLASS Container Bean Client Well-defined interface communication Bound Implements defined method from Component Interface (Remote and Local) Override default Bean class These methods are then called by container manage bean and keep the bean informed of important events EJB can share the propertiess of the serialiable objects because the javax.ejb.EnterpriseBean extends Serializable Once the interface javax.ejb.EnterpriseBean is implemented, the bean class is confirmed

32 DEPLOYMENT DESCRIPTOR
…. <home>Welcomehome</home> <remote>Welcome</remote> <ejb-class>Welcomebean</ejb-class> …… EJB Server/Container Remote Interface, Home Interface, Bean ... The DD points out how the beans must interact with one another Declare middle ware services requirements of components The DD supply the bean component and performs the requirements Life-cycle requirements and bean management: specify how the container should manage the beans Persistence requirements: inform EJB container whether the bean take care of/ or delegate persistence Transaction requirements: support transaction Security management

33 EJB-JAR FILE Component Interface EJB-JAR file (*.jar) Deployment Descriptor Bean class Create jar file Home Interface EJB container decompress, read và extract information contained in the EJB-JAR file. Generation of the EJB object and the home objects, and the bean. (deployer)

34 SESSION BEANS 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 not shareable between clients (only one client can deal with that particular session bean) Enable a Conversation between a client and the J2EE Server Life Cycle of a Session Bean 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 of Session Bean Stateless Session Bean Stateful Session Bean Session bean implement From javax.ejb.Session Bean callback methods (invoked on the bean by the container) business methods Permanent: khong ben vung

35 CONVERSATION & NON-CONVERSATION
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.

36 CALLBACK METHODS public void setSessionContext(SessionContext ctx)
public void ejbCreate([args]) public void ejbPassivate() public void ejbActivate() public void ejbRemove()

37 EJB SESSION CONTEXT setSessionContext() Container Bean Associate Session Context (Gateway) 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() Comprise: bao gom

38 ejb-jar.xml STRUCTURE <?xml version="1.0"?>
<ejb-jar version="2.1" xmlns=" xmlns:xsi=" xsi:schemaLocation=" <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</transaction-type> </session> </enterprise-beans> </ejb-jar>

39 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" " <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>

40 STATELESS SESSION BEAN
Is used for a single request conversation Executes Business operations without maintaining the client state (non-conversation) Lightweight Component – Doesn’t contains complex data structure Same Session Bean instance can handle multiple client requests Improves the scalability of an application Not having instance variables to store information Can’t used when information need to be used various method calls The client has to pass on all the information necessary for the bean through the parameters for the business method. The client is not responsible for the creation or destruction of the bean 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. Spawn: de trung, tao ra

41 LIFE CYCLE OF STATELESS
Start (Does not exist) Client invoke method Client called remove() (or the client times out) init instance ejbRemove() setSessionContext() ejbCreate() Instances (Ready)

42 STATEFUL SESSION BEAN Is used for business processes that span multiple method request or transactions have to be serviced Maintains the State of a client The conversional state must be stored in the bean (Stores client state in instance variable) 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. To passivate a bean a container uses Least Recently Used (LRU) method. 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

43 LIFE CYCLE OF STATEFUL Client invoke method Start (not exist)
Client called remove() (or the client times out) init instance ejbRemove() setSessionContext() Client need more resrc ejbCreate(arg) ejbPassivate() Passivate Client called method on passivate Instances – ready ejbActivate() 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.

44 ACCESSING from CLIENT SIDE
Possible Clients Home Object JNDI lookup Ordinary JavaBean create() Enterprise JavaBean EJB Object Enterprise JavaBean JSP Page Business Methods Servlet Applet

45 [WEB] APPLICATION In EJB
This structure is deployed at JBOSS_HOME\server\default\deploy directory This structure is name with the extension .ear (include jar and war)

46 EJB DEVELOPMENT PROCESS
Requirement: JBoss GA Application Server Step 1: Creating a new EJB Module project 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: Building the project to jar file Step 6: Deploying the project on Application server Step 7: Creating the client application to consume Step 8: Running the client to test the EJB

47 Step 1: Creating a new EJB Module project
Create new Project Choose “Enterprise” on “Categories” Then, choose “EJB Module” on “Projects”. Click Next button

48 Step 1: Creating a new EJB Module project (cont)
Fill your project name Choose the Jboss Server that is added Choose the J2EE1.4 Diverging: hướng nào đó Click Finish button

49 Step 1: Creating a new EJB Module project (cont)

50 Step 2: Creating the new corresponding bean
Choose File menu/ click new File Choose “Enterprise” on “Categories” Then, choose “Session Bean” on “File Types”. Click Next button

51 Step 2: Creating the new corresponding bean (cont)
Fill your bean name Fill or choose the package name Choose stateless or stateful Choose remote or local or both Click Finish button

52 Step 2: Creating the new corresponding bean (cont)
Generate automatically four callback methods: setSessionContext ejbActivate ejbPassivate ejbRemove

53 Step 3: Building/ Modifying the business/callback methods on Beans
Modifying the callback method if necessary Adding a new business method Right click on source code of the Bean file (Ex: CalculateBean) Then, choose EJB Methods, click Add Business Method… Fill or type the method name with return type and all parameters Then, click OK Button

54 Step 3: Building/ Modifying the business/callback methods on Beans (cont)
Cornerstone: important Implement the body of method corresponding with your purpose

55 Step 3: Building/ Modifying the business/callback methods on Beans (cont)

56 Step 4: Mapping the JNDI to beans
Modify the jboss.xml file as following Fill your wanted JNDI that you want to reference

57 Step 5 and 6: Building & Deploying

58 Step 7: Creating the client application to consume
Create Java console application Add reference to EJB project mapping to invoke the remote method on application Server Right click on library of client project/ click “Add Project …” Choose the jar file Modify servlet name Click Add Project Jar File

59 Step 7: Creating the client application to consume (2)
Adding the code as following (notes: addition the jbossall-client.jar and jnp-client.jar from JBOSS_HOME\client to application project) Reference to the application server address (location) Reference to EJB Invoke the remote interface of EJB on Application Server

60 Step 8: Running the client to test the EJB

61 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

62 Step 1: Creating a new Enterprise Application project
Choose the Enterprise in Categories Then, choose the “Enterprise Application” in Projects Click Next Button

63 Step 1: Creating a new Enterprise Application project
Type the Project name Choose the Jboss 4.2.2 Choose J2EE 1.4 Don’t change anything that is default by tools Click Finish Button

64 Step 1: Creating a new Enterprise Application project

65 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 above tutorials in EJB Development process on the xxx-ejb module

66 Step 5: Creating the GUI to consumes EJB on web modules
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 Enterprise Resources, click Call Enterprise Bean

67 Step 5: Creating the GUI to consumes EJB on web modules
Choose the appropriate bean Modify the Reference Name Click Ok Button Modify the Reference Name that is named in jboss.xml at <jndi-name> tag

68 Step 5: Creating the GUI to consumes EJB on web modules
Modifying the code in servlet as following

69 Step 6: Building and Deploying Enterprise application

70 Step 7: Executing the Enterprise Application

71 WORKSHOP ACTIVITIES Building the EJB with stateless and stateful on Java Sun Application Server

72 WORKSHOP ACTIVITIES (cont)
Building the EJB client to consume EJB Application

73 EXERCISES Do it again all of demos, workshops, and the following exercises on JBoss Server Using stateless to write the programs that can do Building checkLogin() method including 02 parameters username & password using DB Building the sayHello() method printing Welcome message with the name as the parameter passing to sayHello() method Using stateful to write the programs that can do Write a Shopping Cart Program using stateful session bean with some functions as add cart, view cart, and remove cart. Write a exchange money program


Download ppt "DEVELOPING ENTERPRISE APPLICATIONS USING EJB"

Similar presentations


Ads by Google