You are on page 1of 33

CHNG 4 THNH PHN EJB (ENTERPRISE JAVA BEAN)

Ti liu dnh cho mn Phn tch thit k, Lp D07CNTT, Hc vin CNBCVT

Mc tiu ca chng ny: Gii thiu J2EE framework v kin trc EJB Gii thiu cc khi nim v Thnh phn EJB v mi trng runtime ca n Tho lun v cc kiu c Thnh phn EJB, kt ni v vic trin khai ca chng Gii thiu cc tnh nng ca EJB 2.x v cc tnh nng mi ca EJB 3.0 Phn bit gia li gi hm ng b v khng ng b. Cung cp hng dn tng bc xy dng, trin khai v s dng Thnh phn EJB

4.1. KIN TRC EJB 4.1.1. Tng quan v kn trc EJB v J2EE platform Sun Microsystems Inc cng b c t Enterprise Java Bean (EJB) ca h vo nm 1998. c t mi ca EJB 2.1 c cng b vo nm 2002. Kin trc EJB 2.x l kin trc thnh phn dnh cho vic pht trin v trin khai cc ng dng phn tn hng thnh phn. Mt Thnh phn EJB l thnh phn c kh nng s dng li, WORA (vit mt ln chy mi ni), kh nng di ng, tnh co dn, v thnh phn c bin dch c th c trin khai trn bt k server EJB no nh l Java 2 platform edition (J2EE), Jboss, v mi trng WebLogic Enterprise. Cng ngh EJB l mt phn ca J2EE, n cung cp mt tp API v cc dch v khc. Vic ci t EJB tp trung vo logic nghip v. J2EE c thit k h tr cc ng dng doanh nghip cung cp cc dch v thng mi. J2EE khng ch h tr EJB m cn h tr cc thnh phn Web nh l JSP v servlets. Kin trc EJB gip cho vic pht trin cc ng dng doanh nghip d dng hn v chng khng cn quan tm n cc dch v mc h thng nh l qun l giao dch, qun l bo mt, qun l a lung, v cc vn qun l chung khc. Kin trc EJB h tr WORA v cc gii php di ng. Mt EJB thnh phn c th c pht trin mt ln sau c th s dng li trong nhiu ng dng v trin khai trn nhiu nn tng khc nhau m khng phi bin dch v sa li m ngun ca Thnh phn EJB. Mt Thnh phn EJB l mt thnh phn pha server cung cp cc dch v cho iu khin t xa hoc client cc b, trong khi mt java bean l mt thnh phn pha client c ci t v chy hu ht pha client. Chng ta c th c mt Java bean pha server nhng kh c th cung cp cc

dch v cho cc client t xa. Mt Thnh phn EJB c cha bi container ca n v container c h tr bi J2EE hoc bt k cng c tun theo J2EE. 4.1.2. J2EE Server J2EE servier cung cp mt s dch v sau: Java Naming and Directory Interface (JNDI) API cho php cc client tm kim v xc nh v tr container, ni cc thnh phn EJB c ng k v cha. J2EE h tr xc thc v u quyn cho cc vn bo mt. J2EE h tr dch v HTTP v cc dch v lin quan n EJB, cc dch v a lung

Hnh 4.1. Kin trc J2EE 4.1.3. EJB Container Mt th hin EJB c chy trn mt EJB container. Container l mi trng chy (tp cc file class c sinh ra trong qu trnh pht trin) n iu khin mt th hin Thnh phn EJB v cung cp tt c cc dch v qun l cn thit cho ton b vng i ca n. Pha di l mt danh sch cc dch v nh vy: Qun l giao tc: m bo cc c tnh giao tc ca vic cc thc thi giao tc phn tn. Qun l lu tr bn vng: m bo trng thi bn vng ca mt entity bean c sao lu bi c s d liu. Qun l vng i : m bo s dch chuyn trng thi ca Thnh phn EJB trong vng i ca n .

Hnh 4.2. EJB container

EJB container cung cp mt giao din cho Thnh phn EJB giao tip vi th gii bn ngoi. Tt c cc yu cu ti Thnh phn EJB hay cc p ng t Thnh phn EJB u phi thng qua EJB container. EJB container c lp Thnh phn EJB n khng b truy nhp trc tip t cc client ca n. Container s chn li gi t client m bo tnh bn vng, cc c tnh giao tc, v an ninh ca cc hot ng ca client trn EJB. Hnh 4.2 ch ra rng EJB h tr EJB componenet v mt Thnh phn EJB cn container i ra bn ngoi v nhn cc thng tin cn thit t giao din ng cnh ca n. EJB container c trnh nhim to ra cc i tng EJB home., gip cho vic xc nh, to ra, v xa b cc i tng Thnh phn EJB. Giao din ng cnh EJB cung cp bi EJB container ng gi cc thng tin lin quan v mi trng ca container nh l dnh danh ca mt Thnh phn EJB, cc trng thi ca giao tc, v tham chiu t xa ti EJB ... 4.1.4. Thnh phn EJB Mt enterprise bean l mt thnh phn phn tn sng trong mt EJB container v c truy cp bi client t trn mng thng qua giao din t xa ca n hoc c truy nhp thng qua enterprise bean khc trn cng server thng qua giao din local ca n. Thnh phn EJB l mt thnh phn c kh nng thc thi t xa c trin khai trn server ca n v c kh nng t m t c ch ra bi Deployment Descriptor (DD) vi nh dng XML. 4.2. M HNH THNH PHN CA EJB 4.2.1. Tng quan v EJB 2.x Mi Thnh phn EJB c mt giao din logic nghip v c to ra bi thnh phn nn cc client c th truy cp vo cc thao tc logic nghip v thng qua giao din ny m khng cn phi bit ci t chi tit ng sau giao din . Chng ta gi giao din nh vy l mt remote interface. Mt th hin ca Thnh phn EJB c to ra v qun l thng qua home interface ca n bi EJB container. Mi enterprise bean phi c mt home interface v mt remote interface. Thnh phn EJB c th c cu hnh ti thi gian trin khai bng c t DD ca n. Hnh 4.3 m t cu trc ca mt Thnh phn EJB v biu qu trnh ca mt tng tc gia mt client v mt Thnh phn EJB.

Hnh 4.3. Tng tc gia client v Thnh phn EJB Lp EJB ng sau cc giao din home v remote c thit k thc thi 2 giao din. Mt Thnh phn EJB l mt thnh phn hp en (black box thnh phn). Client ca mt Thnh phn EJB ch bit thnh phn no ch khng bit n nh th no. Client to mt yu cu ti Thnh phn EJB vi tn c trin khai ca n bng vic tm kim trong JNDI ly tham chiu tham chiu i tng ca Thnh phn EJB. Client sau c th to mt th hin ca Thnh phn EJB ny trn server theo tham chiu i tng. Cui cng, client gi cc phng thc ca th hin EJB ny. Tt nhin mt EJB phi ng k vi JNDI cc client c th tm kim n. Cc Enterprise bean l cc thnh phn phn mm c th c nhng trong nhiu ng dng khc nhau m khng cn phi dch li hoc thay i m ngun ca chng. Chng c th c trin khai trong nhiu my ch tun theo EJB. M hnh Thnh phn EJB h tr nhng loi enterprise bean sau: Stateless session bean thc thi nhiu logic nghip v khc nhau, nh phin dch ngn ng, qu trnh ng nhp, tnh ton thu v chuyn i tin t. Stateless session bean c ng gi trong mt Web service. Bt k mt enterprise bean ang tn ti no cng c th ng gi trong mt Web service bn ngoi bng mt ti liu WSDL m t im cui Web service m bean thc thi. Nhng bean c bit nh vy dng cho cc Web service khng cung cp cc giao din m mt Thnh phn EJB thng cung cp. Stateful session bean cng m trch cng mt vai tr nh cc stateless session bean ngoi tr chng theo vt cc trng thi ca vic giao tip gia t cc client ti cc Thnh phn EJB. V d, mt shopping cart bean c th l mt session bean c trng thi in hnh.

Bt c mtt session bean cho d l c trng thi hay khng trng thi cng khng h tr cc yu cu lu bn cho mt entity bean trong nn tng kin trc Thnh phn EJB:

Message driven bean c gii thiu trn, biu din mt loi Thnh phn EJB mi lm vic trong ch giao tip bt ng b ging nh m hnh y quyn s kin hng s kin (event driven event delegation model) trong Java. Bean Managed Persistence (BMP) l cc entity bean trong khi vic qun tr lu tr lu di ca chng c quan tm bi chnh bn thn chng. Container Managed Persistence l cc entity bean trong vic qun tr lu tr lu di ca chng c c t bi cng c trin khai v c qun l bi container. Tuy nhin cc entity bean CMP khng cn x l bt k vic truy xut c s d liu SQL no. Mt entity bean c phc hi li bi c s d liu quan h.

Remote interface ca mt Thnh phn EJB thc thi giao din javax.ejb.EJBObject sau thc thi giao din java.rmi.Remote. Home interface ca mt Thnh phn EJB thc thi giao din javax.ejb.EJBHome, sau li thc thi giao din java.rmi.remote. Local interface thc thi giao din javax.ejb.EJBLocalObject v mt local home interface thc thi giao din javax.ejb.EJBLocalHome. Local interface c s dng bi Thnh phn EJB khc chy trn cng mt server truy nhp n nn n c th gim chi ph gy ra bi vic truy cp xa. Remote interface cung cp s c lp v tr nhng t hn. Cc local interface to li gi c hiu qu hn. im khc bit quan trng khc gia cc giao din cc b v xa l vic gi phng thc trong giao din cc b s dng vic truyn bng tham chiu v vic gi giao din xa s dng vic truyn bng gi r, m cn phi tun t ha, l t chc v v t chc. 4.2.2. EJB 3.0 Cc c tnh mi ca EJB 3.0: nh ngha cc Java language meta data annotation c th c s dng ch gii (annotate) cc ng dng EJB. Cc metadata annotation ny lm n gin ho cng vic ca nhng nh pht trin, gim s lp v giao din cn phi ci t v ngi pht trin khng cn cung cp mt file m t trin khai (deployment descriptior). ng gi cc ph thuc mi trng v truy cp JNDI thng qua vic s dng cc annotaion, cc c ch tim cc ph thuc (dependency injection) v cc c ch tm kim n gin. n gin ho cc kiu enterprise bean. Khng cn thit cc giao din cho session bean. Giao din nghip v cho mt session bean c th l mt java interface n thun khng cn phi l mt interface EJBObject, EJBLocalObject, hoc java.rmi.Remote. Loi b cc yu cu cho home interface ca session bean.

n gin ho cc entity bean. H tr m hnh ho min hng nh, cung cp k tha v a hnh. Loi b tt c cc giao din cho persistent entity. c t cc Java language metadata annotaion v XML deployment descriptor cho vic nh x cc quan h ca persistent entity.

Cc v d di y s s dng c EJB 3.0 v EJB 2.x. 4.2.3. Session bean Mt sesion bean biu din mt client n bn trong Application Server. truy xut mt ng dng c trin khai trn server, client gi cc phng thc ca session bean. Session bean thc hin cng vic cho cc client ca n. Trnh cho client phi thc hin cc cng vic phc tp, thay v n s c thc hin trn server. Ging nh tn ca n, session bean ging nh mt phin tng tc (interactive session). Mt session bean khng th chia s, n ch c th c mt client. Ging nh mt phin tng tc, mt session bean khng persistent (d liu ca n khng c lu vo c s d liu). Khi client gt, session bean ca n cng b ngt, n khng kt ni lu di vi client. C 2 kiu session bean l stateful v stateless: Stateful session bean: Trng thi ca mt i tng bao gm gi tr ca cc bin. Trong mt stateful session bean, cc gi tr biu din trng thi ca mt session bean cho duy nht mt client. V client tng tc vi bean ca n, trng thi ny thng c gi l trng thi m thoi. Trng thi ny c duy tr trong sut phin lm vic gia client v bean. Nu client loi b bean hoc ngt, phin kt thc v cc trng thi s mt. Stateless session bean: khng duy tr trng thi m thoi vi client. Khi mt client gi cc phng thc ca mt client khng trng thi, cc bin ca bean c th cha mt trng thi c th cho mt client, nhng ch trong thi gian ca li gi. Khi phng thc hon thnh, trng thi ny s b mt. Tuy nhin, cc cleint c th thay i trng thi ca cc bin trong stateless bean c pool (pooled stateless bean), trng thi ny s c gi n li gi tip theo ca pooled stateless bean. V stateless session bean c th h tr nhiu client, chng c th a ra tnh kh chuyn hn cho cc ng dng i hi s client ln. c bit, mt ng dng yu cu t stateless session bean hn stateful session bean h tr cng s client.

V d v stateless session bean, bean ny thc hin vic chuyn i F sang C v ngc li.
//remote interface: Converter package converter.ejb; import javax.ejb.Remote; @Remote

public interface Converter { public double cToF(double c); public double fToC(double f); } //stateless session bean: ConverterBean package converter.ejb; import javax.ejb.Stateless; @Stateless public class ConverterBean implements Converter { @Override public double cToF(double c) { return c * 9/5 + 32; } @Override public double fToC(double f) { return (f - 32) * 5/9; } }

4.2.4. EJB Web Service Thnh phn Mt web service client c th truy xut mt ng dng Java EE theo 2 cch. Mt l, client c th truy xut mt web service c to vi JAX-WS. Hai l, mt web service client c th gi phng thc ca mt stateless session bean. Web service s dng cc giao thc (SOAP, HTTP, WSDL), bt k web service client no cng c th truy cp mt stateless session bean, client c th c vit bng ngn ng Java hoc mt ngn ng khc. Client khng cn bit cng ngh ci t cc service: stateless session bean, JAX WS, hoc cc cng ngh khc. Thm na, cc enterprise bean v cc thnh phn web c th l cc client ca web service. Tnh linh hot ny cho php bn tch hp cc ng dng Java EE vi web service. Mt web service client c th truy xut mt stateless session bean thng qua lp ci t im cui web service ca bean. Tt c cc phng thc public trong bean c th c truy cp bi cc web service client. Di y l v d HelloService, dch v web HelloService l mt stateless session bean.
Package ejb.service; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebService; @Stateless @WebService public class HelloServiceBean { private String message = "Hello, ";

public void HelloServiceBean() { } @WebMethod public String sayHello(String name) { return message + name + "."; } }

4.2.5. Entity Bean Mt entity bean biu din mt d liu bn c sao lu bi mt c s d liu. Cc sinh vin, cc gio vin, v cc kha hc l nhng v d ca entity bean. Mi entity bean c mt bng trong c s d liu v mi th hin ca bean c lu gi trong mt hng ca bng. Mt entity khng tng ng vi bt k mt khch hng c th no. N cung cp mt truy cp c chia s. N c h tr bi dch v giao tc EJB qua container ca n. N c mt trng thi bn vi mt nh danh kha chnh duy nht, c th c s dng bi mt client xc nh v tr mt entity bean c th. Vi EJB 2.x, c 2 loi entity bean :cc entity bean Bean Managed Persistence (BMP) v cc entity bean Container Managed Persistence (CMP). y l mt v d ca entity bean BMP sinh vin. Mt bng c s d liu phi c to bng SQL :
CREATE TABLE student (id VARCHAR(3) CONSTRAINT pk_student PRIMARY KEY, gpa Number(2,1) ); //The following is the home interface for this student BMP entity //bean. import javax.ejb.*; import java.util.*; public interface StudentHome extends EJBHome { public Student create(String id, double gpa) throws RemoteException, CreateException; public Account findByPrimaryKey(String id) throws FinderException, RemoteException; } //The following code is the remote interface for this student BMP //entity bean. import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Student extends EJBObject { public double getGpa() throws RemoteException; } //The following is the BMP implementation entity bean where SQL //statements are explicitly included. import java.sql.*; import javax.sql.*; import java.util.*; import javax.ejb.*;

import javax.naming.*; public class StudentEJB implements EntityBean { private String id; private double gpa; private EntityContext context; private Connection con; private String dbName = "java:comp/env/jdbc/StudentDB"; public double getGpa() { return gpa; } //The following ejb callback methods are executed by EJB //container. The Detailed references are in this chapter //reference.[1] //When a new bean instance is created the method ejbCreate() // is automatically called by the container to insert a row in a //corresponding table in the database. public String ejbCreate(String id, double gpa) throws CreateException { try { insertRow(id, gpa); } catch (Exception ex) { throw new EJBException("ejbCreate: "); } this.id = id; this.gpa = gpa; return id; } public String ejbFindByPrimaryKey(String primaryKey) throws FinderException { boolean result; try { result = selectByPrimaryKey(primaryKey); } catch (Exception ex) { throw new EJBException("ejbFindByPrimaryKey: "); } if (result) { return primaryKey; } else { throw new ObjectNotFoundException ("Row for id " + primaryKey + " not found."); } } public void ejbRemove() { try { deleteRow(id); } catch (Exception ex) {

throw new EJBException("ejbRemove: "); } } public void setEntityContext(EntityContext context) { this.context = context; try { makeConnection(); } catch (Exception ex) { throw new EJBException("Failed to connect todatabase.); } } public void ejbActivate() { id = (String)context.getPrimaryKey(); } public void ejbPassivate() { id = null; } public void ejbLoad() { try { loadRow(); } catch (Exception ex) { throw new EJBException("ejbLoad: "); } } public void ejbStore() { try { storeRow(); } catch (Exception ex) { throw new EJBException("ejbLoad: " ); } } public void ejbPostCreate(String id, double gpa) { } void makeConnection() throws NamingException, SQLException { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); } //The following methods are callback methods to invoke SQL //statements to access database void insertRow (String id, double gpa) throws SQLException { String insertStatement = "insert into student values(?,? )"; PreparedStatement prepStmt = con.prepareStatement(insertStatement);

prepStmt.setString(1, id); prepStmt.setDouble(2, gpa); prepStmt.executeUpdate(); prepStmt.close(); } void deleteRow(String id) throws SQLException { String deleteStatement = "delete from student where id = ?"; PreparedStatement prepStmt=con.prepareStatement(deleteStatement); prepStmt.setString(1, id); prepStmt.executeUpdate(); prepStmt.close(); } boolean selectByPrimaryKey(String primaryKey) throws SQLException { String selectStatement="select id "+"from student where id =? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, primaryKey); ResultSet rs = prepStmt.executeQuery(); boolean result = rs.next(); prepStmt.close(); return result; } void loadRow() throws SQLException { String selectStatement = "select gpa " + "from student where id = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, this.id); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { this.gpa = rs.getDouble(2); prepStmt.close(); } else { prepStmt.close(); throw new NoSuchEntityException(id + " not found."); } } void storeRow() throws SQLException { String updateStatement = "update student set gpa = ? " + "where id = ?"; PreparedStatement prepStmt = con.prepareStatement(updateStatement); prepStmt.setDouble(1, gpa);

prepStmt.setString(2, id); int rowCount = prepStmt.executeUpdate(); prepStmt.close(); if (rowCount == 0) { throw new EJBException("Store id failed."); } } }

"

id

"

Vi JavaEE 5 c th s dng JPA (Java Persistent API) to ra cc entity nh x vo cc bng trong c s d liu. V d di y l mt entity bean BookEntity v mt stateless session bean BookBean c cc phng thc to, xo, sa, tm kim thng tin sch trong c s d liu.
//EntityBean: BookEntity package ejb.book; import import import import import import import java.io.Serializable; javax.persistence.Column; javax.persistence.Entity; javax.persistence.GeneratedValue; javax.persistence.GenerationType; javax.persistence.Id; javax.persistence.NamedQuery;

@Entity @NamedQuery(name = "findAllBooks", query = "SELECT b FROM Book b") public class BookEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false) private String title; private float price; @Column(length = 2000) private String description; private String isbn; private int nbOfPage; private boolean illustrations; public BookEntity() { } public BookEntity(Long id, String title, float price, String description, String isbn, int nbOfPage, boolean illustrations) { this.id = id; this.title = title; this.price = price;

this.description = description; this.isbn = isbn; this.nbOfPage = nbOfPage; this.illustrations = illustrations; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isIllustrations() { return illustrations; } public void setIllustrations(boolean illustrations) { this.illustrations = illustrations; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public int getNbOfPage() { return nbOfPage; } public void setNbOfPage(int nbOfPage) { this.nbOfPage = nbOfPage; } public float getPrice() { return price; } public void setPrice(float price) {

this.price = price; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof BookEntity)) { return false; } BookEntity other = (BookEntity) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.me.bookws.Book[id=" + id + "]"; } } //Remote Interface: BookRemote package ejb.book; import java.util.List; import javax.ejb.Remote; @Remote public interface BookRemote { void create(BookEntity book); void edit(BookEntity book);

void remove(BookEntity book); BookEntity find(Object id); List<BookEntity> findAll(); List<BookEntity> findRange(int[] range); int count(); } //Stateless session bean: BookBean package ejb.book; import import import import import import import java.util.List; javax.ejb.Stateless; javax.persistence.EntityManager; javax.persistence.PersistenceContext; javax.persistence.Query; javax.persistence.criteria.CriteriaQuery; javax.persistence.criteria.Root;

@Stateless public class BookBean implements BookRemote { @PersistenceContext(unitName = "BookWSPU") private EntityManager em; public void create(BookEntity book) { em.persist(book); } public void edit(BookEntity book) { em.merge(book); } public void remove(BookEntity book) { em.remove(em.merge(book)); } public BookEntity find(Object id) { return em.find(BookEntity.class, id); } public List<BookEntity> findAll() { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(BookEntity.class)); return em.createQuery(cq).getResultList(); }

public List<BookEntity> findRange(int[] range) { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(BookEntity.class)); Query q = em.createQuery(cq); q.setMaxResults(range[1] - range[0]); q.setFirstResult(range[0]); return q.getResultList(); } public int count() { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<BookEntity> rt = cq.from(BookEntity.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } }

4.2.6. Message-Driven Beans (MDB) Mt message driven bean l mt enterprise bean cho php cc ng dng Java EE x l cc message theo cch khng ng b. N hot ng nh mt b lng nghe thng ip JMS, n ging nh b nh mt b lng nghe s kin tr khi n nhn cc thng ip JMS theo cc s kin. Cc thng ip c th c gi bi bt k thnh phn Java EE no (cc ng dng client, mt enterprise bean khc, web thnh phn) hoc bi mt ng dng JMS hoc h thng khng s dng cng ngh Java. Message drivent bean c th xl cc thng ip JMS hoc cc kiu thng ip khc. Message driven bean c th lm vic theo cch khc nhau: PTP (point to point) v nh xut bn/ ngi ng k (publisher/subcriber). PTP lm vic trong ch mt mt (one-to-one) v publisher/subscriber lm vic trong ch qung b (mt - nhiu :one-to-many). Cng ngh MDB lm vic trong ch khng ng b trong mt thng bo c th c nhn bi mt MDB thnh phn v cc phn ng ca n c th ngay lp tc hoc lu. Mt MDB thnh phn lm vic theo cch sau :
Container ng k MDB thnh phn ny vi JMS JMS ng k tt c cc ch JMS vi Java Naming v Directory Interface (JNDI). EJB container th hin MDB thnh phn ny Client tm kim ch vi MDB Client gi thng ip n ch EJB container chn MDB tng ng x l gi tin

MDB thnh phn lm vic trong ch publisher/subscriber khng ng b v loi thng ip c th l tin nhn vn bn, cc tin nhn i tng, tin nhn dng, hoc tin nhn byte.

Cc gi tin c y v x l trong mt phng thc MessageListener c gi l onMessage(). V d di y xy dng mt Message driven bean x l cc thng ip vn bn n (TextMessage).
//MessageDrivenBean: SimpleMessageBean package ejb.mdb; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.jms.MessageListener; import javax.jms.Message; import javax.jms.TextMessage; import javax.jms.JMSException; import javax.annotation.Resource; @MessageDriven(mappedName = "jms/Queue") public class SimpleMessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; public SimpleMessageBean() { } @Override public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " + msg.getText()); } else { System.out.println( "Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } } }

4.3. M HNH KT NI CA EJB Trong phn ny, chng ta s tho lun v cc c ch kt ni gia cc thnh phn EJB. Chng ta s tm hiu cch lin kt thnh phn c bn thnh cc khi to thnh cc thnh phn mi hoc cc ng dng mi. M hnh kt ni ca EJB a ra cc hng dn

trong thit k cc Thnh phn EJB, cc kt ni, v cc giao tip gia cc thnh phn. [thnh phn 2004]. cho mt i tng client Thnh phn EJB ni vi cc i tng Thnh phn EJB khc, client phi ly c mt i tng tham chiu ti thnh phn ch v mt th hin t xa (RMI). iu ny c th c thy t v d chuyn i nhit . C th c cc kt ni ng b hoc khng ng b gia 2 EJB thnh phns thng qua interface t xa hoc cc b ca cc Thnh phn EJB. Mt Thnh phn EJB cng c th c truy cp bng J2EE Web thnh phn cng nh mt JavaBean thnh phn, mt Servlet thnh phn, hoc mt JSP thnh phn. Mt EJB thnh phn cng c th truy cp cc i tng d liu khc ca EIS bng JDBC. Hnh 4.4 biu th mt session bean pha trc kt ni vi 2 entity bean pha sau bng mt c s d liu.

Hnh 4.4. Kt ni gia session bean v entity bean 4.3.1. Cc kt ni ng b c kt hp kn Mt li gi ng b theo m hnh tng tc yu cu - phn hi. Mt client gi mt phng thc t xa trong interface ca i tng Thnh phn EJB ch. Interface che du tt c vic ci t chi tit cc phng thc logic nghip v ca cc client. Sau khi i tng Thnh phn EJB ch kt thc cng vic ca n, n s p tr cc yu cu bng vic gi kt qu hoc n c th yu cu cc dch v khc t cc thnh phn khc v ch phn hi ri chuyn ti client. Mt v d in hnh cho kiu truyn thng ny, mt gi mua hng session bean s gi mt yu cu ti mt entity bean v ch bean x l v xc nhn. S tng tc ng b lm cho s kt hp cc Thnh phn EJB thm cht ch. Khi mt i tng client thnh phn khi to 1 yu cu, lung yu cu c kha cho n khi n nhn c tr

li t Thnh phn EJB ch. Hu ht cc v d chng ta thy cho n nay u hot ng ch ng b. 4.3.2. Truyn thng khng ng b c kt ni lng lo Mt truyn thng khng ng b gm truyn thng da trn thng ip gia mt Thnh phn EJB v client ca n. Mt client to mt request ti mt Thnh phn EJB nhng client khng t n block. Thay vo n duy tr tin trnh ca mnh. C 2 hnh thc ca truyn thng khng ng b : PTP da trn hng i (queue based PTP) v qung b thng ip da trn publish/subscribe (publish/subscribe based message broadcasting). Truyn thng khng ng b da trn hng i yu cu mt hng i thng ip c h tr bi JMS gia client (ngi cung cp message hoc ngi gi ) v ngi nhn message hoc ngi dng message. Cn phng php publisher/subscriber , ngi dng ng k ch (topic) trong ngi cung cp t cc message vo v mt hoc nhiu ngi dng c th nhn thng ip t ch ny. Trong truyn thng khng ng b , cc client v server u kt ni lng lo. N dn n thng lng tt hn. 4.3.3 Truyn thng Remote v Local Mt thnh phn client v server ca n c th trn mt my hoc trn cc JVM khc nhau. Nu 2 Thnh phn EJB chy trn cng mt my, s c chi ph thp nhiu bi s dng local interface so vi s dng remote interface. l vic ti sao EJB 2.x thm cc interface localHome v localObject vo remote interface. Mt vi thc th bean c th cung cp c 2 interface remote v local trong EJB 2.x . Mt session bean c th ng vai tr ca thc th bean, v mt thc th bean c th biu din trc tip vi client hoc thng qua mt session bean hoc c kt ni ti thc th bean khc. Mt local interface cho php tham chiu ti mt phng thc trong m hnh truyn tham chiu, trong khi mt remote interface thc hin n trong m hnh truyn tham tr. 4.3.4. Cc tham chiu i tng n cc entity bean ni ti mt entity bean ch, mt stateless session bean phi tm cc thnh phn c trin khai theo tn ca n ng k ti JNDI ly mt tham chiu i tng ti n v c th qua tham chiu ti cc bean khc. Mt stateful session bean c th gi tham chiu ti mt thc th bean trong mt trng thi m thoi. Mt session bean hoc MDB thnh phn c th gi vic tham chiu ti Thnh phn EJB khc trong mt th hin ca bean ca n. Mt entity bean BMP c th gi mt tham chiu ti entity bean khc trong phm vi khng lu di. 4.3.5. Lin kt cc quan h kt ni gia cc entity bean Vi EJB 2.x, mi thc th bean lu tr bi 1 bng quan h. Mi th hin ca mt thc th bean c lu l 1 hng trong bng bt k BMP hay CMP. Cc quan h gia cc thc th bean c th mt - mt, mt - nhiu , nhiu - nhiu, ging nh cc mi quan h d liu trong mt c s d liu c phn nh trong biu E - R.

V d, quan h gia entity bean sinh vin (student) v entity bean kho hc (course) l mt quan h nhiu nhiu. Mt sinh vin c th c nhiu kha hc v mt kha hc c th c nhiu sinh vin. Thc hin cc thc th bean ny bng CMP trong kin trc EJB 2.x . Gi s c 2 thc th bean CMP c trin khai ti mt container nh vy local interface c s dng.
package student; import import import import import import java.util.*; javax.ejb.CreateException; javax.ejb.EntityBean; javax.ejb.EntityContext; javax.naming.Context; javax.naming.InitialContext;

public abstract class StudentBean implements EntityBean { private EntityContext context; //StudentID and StudentName are CMP fields public abstract String getStudentID(); //primary key public abstract void setStudentID(String id); public abstract String getName(); public abstract void setName(String lastName); //CMR(container-managed relationship) fields to course bean public abstract Collection getCourses(); public abstract void setCourses (Collection courses); //StudentBean next defines its business logic such that //getCourseList() //returns all corresponding courses this student has taken and //addCourse() will add a new course for this student. public ArrayList getCourseList() { ArrayList list = new ArrayList(); Iterator c = getCourses().iterator(); while (c.hasNext()) { list.add( (LocalCourse)c.next()); } return list; } public void addCourse (LocalCourse course) { getCourses().add(course); } } //Student Local Home Interface Heres the LocalStudentHome home interface for the StudentBean: import javax.ejb.CreateException; import javax.ejb.EJBLocalHome; import javax.ejb.FinderException;

public interface LocalStudentHome extends EJBLocalHome { public LocalStudent create (String studentID, String Name) throws CreateException; public LocalStudent findByPrimaryKey ( String studentID)throws FinderException; } } //The Student bean also defines a local interface. The beans //LocalStudent interface extends the EJBLocalObject interface //not the EJBObject interface. import java.util.ArrayList; import javax.ejb.EJBLocalObject; public interface LocalStudent extends EJBLocalObject { public String getStudentID(); public String getName(); public ArrayList getCourseList(); }

y chng ta ch c danh sch entity CMP sinh vin, v entity bean CMP kha hc c cu trc rt ging nhau tr trng cmp v cmr. Bean kho hc bao gm cc phng thc tng ng get v set tt c cc sinh vin c lin kt ti kha hc c th.
public abstract Collection getStudents(); public abstract void setStudents(Collection students);

DD ch r mi quan h enterprise bean. Cng c trin khai c th c s dng trong c 2 lnh vc CMP v CMR , quan h bean-to-bean v code EJB SQL cho cc phng php c th.

Hnh 4.5. Quan h kt ni gia cc entity bean Trong hnh 4.5, c 3 thc th bean CMP. Dept c quan h mt - nhiu vi entity bean student v entity bean student c quan h nhiu nhiu vi entity bean Course. Tt c

quan h bean -bean, cmp v cmr, v vic thc thi ca cc phng thc trong SQL c nh ngha bi ngi trin khai s dng cc cng c trin khai. Trong s so snh, BMP i hi nhiu vic phi lm bi ngi trin khai, trong khi CMP khng i hi ngi lp trnh cung cp bt c m SQL no. 4.4. M HNH TRIN KHAI EJB Mt EJB componenet c ng gi vo mt flie .jar, sau n s c t hp vi cc gi Web thnh phn (.war) v cc gi ng dng client J2EE trong file ng dng J2EE (.ear). Sau khi vit code cho enterprise bean v client ca n, chng ta cn dch chng thnh cc class file. Tip , chng ta cn gi cc Thnh phn EJB, Web thnh phn, hoc client vo file nn java (.jar) hoc Web archive file (.war) vi flie DD XML ca chng v sau lp rp tt c cc phn ny v nn thnh mt file enterprise (.ear) c trin khai trn mt server. Mt DD lm mt file nh ngha trin khai nh dng XML. N nu ra cc loi EJB, tn cc class cho giao din t xa, giao din home, vic ci t bean, c t qun l giao dch, an ninh truy nhp, v cc c tnh bn vng ca entity bean. DD c to t ng bi cc cng c trin khai sau khi khung trin khai c han thnh. Di y l mt phn ni dung ca mt DD:
<?xml version=1.0> <ejb-jar> <enterprise-beans> <entity> <ejb-name>studentBean</ejb-name> <home>studenthome</home> <remote>student</remote> <ejb-class>Student</ejb-class> <persistence-type>Container</persistence-type> <pri-key-class>Integer</pri-key-class> ... <cmp-field><field-name>id</field-name></cmp-field> ... <cmp-field><field-name>name</field-name></cmp-field> </enterprise-beans> <assembly-descriptor> <security-role> ... </security-role> ... </assembly-descriptor> </ejb-jar>

Hnh 4.6. J2EE assembly v deployment

4.5. V D Phn ny c thit k nng cao s hiu bit v cc khi nim EJB qua mt v d c th v cc ch dn tng bc gii thch lm th no xy dng cc thnh phn EJB, lm th no kt hp li v trin khai cc thnh phn EJB. 4.5.1. V d Shopping Cart Session bean cart biu din mt shopping cart trong bookstore trc tuyn. Client ca bean c th thm, xo sch ra khi gi, ly li ni dung ca gi sch. Cn xy dng 2 file sau: Session bean class (CartBean) Remote business interface (Cart)

Bc 1: Xy dng Business Interface Cart business interface l mt giao din Java nh ngha tt c cc phng thc c ci t trong lp bean. Nu lp bean ci t mt interface, th interface c gi l business interface. Business interface l mt giao din local interface tr khi n c nh du vi annotation javax.ejb.Remote.
package cart.ejb; import cart.util.BookException; import java.util.List; import javax.ejb.Remote; @Remote public interface Cart { public void initialize(String person) throws BookException; public void initialize( String person,

String id) throws BookException; public void addBook(String title); public void removeBook(String title) throws BookException; public List<String> getContents(); public void remove(); }

To lp bt ngoi l BookException
package cart.util; public class BookException extends Exception { public BookException() { } public BookException(String msg) { super(msg); } }

Bc 2: Xy dng lp Bean Ging nh bt k stateful session bean, CartBean phi t cc yu cu sau: Class phi c ch thch @Stateful Class ci t cc phng thc nh ngha trong business interface Thc thi business interface Ci t cc phng thc life cycle callback, ch thch @PostConstruct, @PreDestroy, @PostActivate, @PrePassivate Ci t cc phng thc tu chn ch thch @Remote

Stateful session bean cng c th c:

Package cart.ejb; import import import import import import cart.util.BookException; cart.util.IdVerifier; java.util.ArrayList; java.util.List; javax.ejb.Remove; javax.ejb.Stateful;

@Stateful() public class CartBean implements Cart { List<String> contents; String customerId; String customerName; public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else {

customerName = person; } customerId = "0"; contents = new ArrayList<String>(); } public void initialize( String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); } contents = new ArrayList<String>(); } public void addBook(String title) { contents.add(title); } public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (result == false) { throw new BookException("\"" + title + "\" not in cart."); } } public List<String> getContents() { return contents; } @Remove() public void remove() { contents = null; } }

Bc 3: Xy dng client
package cart.client; import import import import import java.util.Iterator; java.util.List; javax.ejb.EJB; cart.ejb.Cart; cart.util.BookException;

/** * * The client class for the CartBean example. Client adds books to the cart, * prints the contents of the cart, and then removes a book which hasn't been * added yet, causing a BookException. * @author ian */ public class CartClient { @EJB private static Cart cart; public CartClient(String[] args) { } /** * @param args the command line arguments */ public static void main(String[] args) { CartClient client = new CartClient(args); client.doTest(); } public void doTest() { try { cart.initialize("Duke d'Url", "123"); cart.addBook("Infinite Jest"); cart.addBook("Bel Canto"); cart.addBook("Kafka on the Shore"); List<String> bookList = cart.getContents(); bookList = cart.getContents(); Iterator<String> iterator = bookList.iterator(); while (iterator.hasNext()) { String title = iterator.next(); System.out.println ("Retrieving book title from

cart:

"

title); } System.out.println ("Removing cart."); cart.removeBook("Gravity's Rainbow"); cart.remove(); System.exit(0); } catch (BookException ex) { System.err.println ("Caught a BookException: ex.getMessage()); System.exit(1); } catch (Exception ex) { System.err.println("Caught an exception!"); ex.printStackTrace(); System.exit(1); } } }

\"Gravity's

Rainbow\"

from

"

unexpected

Bc 4: Build v ng gi ng dng >ant Bc 5: Trin khai ng dng > ant deploy cart.ear c trin khai trn server Bc 6: Chy Cart Client > ant run Kt qu: [echo] running application client container. [exec] Retrieving book title from cart: Infinite Jest [exec] Retrieving book title from cart: Bel Canto [exec] Retrieving book title from cart: Kafka on the Shore [exec] Removing "Gravitys Rainbow" from cart. [exec] Caught a BookException: "Gravitys Rainbow" not in cart. [exec] Result: 1

4.5.2. Xy dng Converter s dng netbean V d Converter chuyn i t F sang C v ngc li. S dng netbean xy dng ng dng. Bc 1: To ejb module converter-ejb

Bc 2: To mt business interface Converter package converter.ejb; import javax.ejb.Remote; /** * * @author HP */ @Remote public interface Converter { public double cToF(double c); public double fToC(double f); } Bc 3: To bean ConverterBean: ConverterBean l Stateless Session bean thc thi giao din Converter package converter.ejb; import javax.ejb.Stateless;

@Stateless public class ConverterBean implements Converter { @Override public double cToF(double c) { return c * 9/5 + 32; } @Override public double fToC(double f) { return (f - 32) * 5/9; } } Bc 4: Build converter-ejb Click chut phi vo converter-ejb chn build build project Bc 5: To mt ng dng web s dng converter-ejb: converter-war

Bc 5: Add converter-ejb vo library ca converter-war

Bc 5: To file index.jsp trong converter-war <%@ <%@ <%@ <%@ <%@ <%@ <%! private Converter converter = null; public void jspInit() { try { InitialContext ic = new InitialContext(); converter = (Converter) ic.lookup(Converter.class.getName()); } catch (Exception ex) { System.out.println ("Couldn't create converter bean."+ ex.getMessage()); } } public void jspDestroy() { converter = null; } %> <html> <head> <title>Temperature Converter</title> </head> <body bgcolor="white"> <h1><b><center> Temperature Converter </center></b></h1> <hr> page page page page page page import="converter.ejb.Converter, javax.naming.*"%> import="java.math.*"%> import="javax.naming.*"%> import="javax.ejb.*" %> import="java.text.DecimalFormat" %> import="java.rmi.RemoteException" %>

<p>Enter a degree to convert:</p> <form method="get"> <input type="text" name="degree" size="25"> <br> <p> <input type="submit" name="fToC" value="Fahrenheit to Centigrade"> <input type="submit" name="cToF" value="Centigrade to Fahrenheit"> </form> <% DecimalFormat twoDigits = new DecimalFormat ("0.00"); String degree = request.getParameter("degree"); if ( degree != null && degree.length() > 0 ) { double d = Double.parseDouble(degree); %> <% if (request.getParameter("fToC") != null ) { %> <p> <%= degree %> fahrenheit degrees are <%= twoDigits.format(converter.fToC(d)) %> centigrade degrees. <% } %> <% if (request.getParameter("cToF") != null ) { %> <p> <%= degree %> centigrade degrees are <%= twoDigits.format (converter.cToF(d)) %> fahrenheit degrees . <% } %> <% } %> </body> </html> Bc 6: Built project converter-war Click chut phi vo converter chn build Bc 7: Chy project converter-war Kt qu:

4.6. KT LUN EJB 2.x cung cp mt c s h tng thnh phn tng t nh CORBA 3.0. M hnh thnh phn ca cng ngh EJB c s dng trong vic xy dng ng dng Java enterprise trong mi trng phn tn. Bt c thnh phn EJB no cng c 2 interface v mt lp bean thc thi interface. giao din home EJB qun l vng i ca mt i tng EJB nh to, xo mt th hin,v tm kim mt th hin bean thc th bng kha chnh.interface EJB cung cp v th hin tt c phng thc logic business logic c s dng bi client ca n. Thc thi lp bean m rng mt lp sesion bean hay lp bean entity,trin khai da trn kiu ca thnh phn EJB. C hai kiu ca session bean, stateless v stateful,v c hai u hot ng da trn cc hnh vi ca client ca n. Thnh phn Stateless EJB khng lu gi cc thng tin trng thi trong sut phin ca chng nh mt my tnh in t online. Mt khc stateful session bean cn lu gi vi thng tin v trng

thi trong sut phin ca chng. Chng hn, mt session bean shopping cart cn theo di vic thu thp ca mc hng ca client. C hai kiu ca entity bean - BMP v CMP c hai u s dng tng back - end kt ni n database v h tr vic lu tr. Mi entity bean c mt bng quan h sau n. Mi th hin ca thnh phn entity EJB c lu tr trong bng nh l mt ct. CMP entity bean c t do truy cp code trong SQLv nh x n database c hon thnh bi developer trong thi gian trin khai. EJB 3.0 c mt s c tnh mi gip cho ngi pht trin d dng hn trong vic ci t v trin khai cc enterprise bean. Bt k thnh phn EJB no c nh gi qua cc EJB container, n cung cp cc dch v cn thit v to ra cc EJB kh chuyn hn. Mt thnh phn EJB c ng gi, hp, v trin khai trn server.

You might also like