我的Session Bean Container实现(1)

弘伟彦
2023-12-01
一直想写点什么,但是一直没有下手,今天来了兴趣,写点有关如何构造Session Bean Container的问题。

第一节    一个Session Bean的例子

让我们看看一个Session Bean的例子,下面是Sun的J2EE中的教程一个图书购物车的例子:

Home接口

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;


public interface CartHome extends EJBHome {
    Cart create(String person) throws RemoteException, CreateException;

    Cart create(String person, String id)
        throws RemoteException, CreateException;
}

Remote接口

import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;


public interface Cart extends EJBObject {
    public void addBook(String title) throws RemoteException;

    public void removeBook(String title) throws BookException, RemoteException;

    public Vector getContents() throws RemoteException;
}

Bean 实现

import java.util.*;
import javax.ejb.*;


public class CartBean implements SessionBean {
    String customerName;
    String customerId;
    Vector contents;

    public CartBean() {
    }

    public void ejbCreate(String person) throws CreateException {
        if (person == null) {
            throw new CreateException("Null person not allowed.");
        } else {
            customerName = person;
        }

        customerId = "0";
        contents = new Vector();
    }

    public void ejbCreate(String person, String id) throws CreateException {
        if (person == null) {
            throw new CreateException("Null person not allowed.");
        } else {
            customerName = person;
        }

        IdVerifier idChecker = new IdVerifier();

        if (idChecker.validate(id)) {
            customerId = id;
        } else {
            throw new CreateException("Invalid id: " + id);
        }

        contents = new Vector();
    }

    public void addBook(String title) {
        contents.addElement(title);
    }

    public void removeBook(String title) throws BookException {
        boolean result = contents.removeElement(title);

        if (result == false) {
            throw new BookException(title + " not in cart.");
        }
    }

    public Vector getContents() {
        return contents;
    }

    public void ejbRemove() {
    }

    public void ejbActivate() {
    }

    public void ejbPassivate() {
    }

    public void setSessionContext(SessionContext sc) {
    }
}


Sun的教程中,只要求我们提供这三个java源代码文件,然后编译打包,在Application Server中部署。当我们按照Sun的规范编写网络客户端程序,就可以通过网络调用Remote接口Cart中的定义的方法。


让我们看看Sun写的客户端程序吧

/*
 * Copyright (c) 2004 Sun Microsystems, Inc.  All rights reserved.  U.S.
 * Government Rights - Commercial software.  Government users are subject
 * to the Sun Microsystems, Inc. standard license agreement and
 * applicable provisions of the FAR and its supplements.  Use is subject
 * to license terms.
 *
 * This distribution may include materials developed by third parties.
 * Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
 * or registered trademarks of Sun Microsystems, Inc. in the U.S. and
 * other countries.
 *
 * Copyright (c) 2004 Sun Microsystems, Inc. Tous droits reserves.
 *
 * Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
 * commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
 * licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
 * en vigueur de la FAR (Federal Acquisition Regulations) et des
 * supplements a celles-ci.  Distribue par des licences qui en
 * restreignent l'utilisation.
 *
 * Cette distribution peut comprendre des composants developpes par des
 * tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
 * sont des marques de fabrique ou des marques deposees de Sun
 * Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
 */


import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;


public class CartClient {
    public static void main(String[] args) {
        try {
            Context initial = new InitialContext();
            Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");

            CartHome home =
                (CartHome) PortableRemoteObject.narrow(objref, CartHome.class);

            Cart shoppingCart = home.create("Duke DeEarl", "123");

            shoppingCart.addBook("The Martian Chronicles");
            shoppingCart.addBook("2001 A Space Odyssey");
            shoppingCart.addBook("The Left Hand of Darkness");

            Vector bookList = new Vector();

            bookList = shoppingCart.getContents();

            Enumeration enumer = bookList.elements();

            while (enumer.hasMoreElements()) {
                String title = (String) enumer.nextElement();

                System.out.println(title);
            }

            shoppingCart.removeBook("Alice in Wonderland");
            shoppingCart.remove();

            System.exit(0);
        } catch (BookException ex) {
            System.err.println("Caught a BookException: " + ex.getMessage());
            System.exit(0);
        } catch (Exception ex) {
            System.err.println("Caught an unexpected exception!");
            ex.printStackTrace();
            System.exit(1);
        }
    }
}


关键语句:
1)    初始化Context和获取CartHome的Reference,这个过程就想CORBA的Naming Service, 不难理解

Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");

2) 调用PortableRemoteObject.narrow()将从网络获取的Reference(类是于网址, 如: http://baidu.com)转换为CartHome对象 (CartHome是一个接口,可从来没有实现过哟, 有点神奇)


CartHome home =
                (CartHome) PortableRemoteObject.narrow(objref, CartHome.class);

3) 有了CartHome对象,就可以调用他的方法创建一个Cart对象(Cart接口也是没有实现的哟,怎么回事?EJB Container为我们实现了?)

Cart shoppingCart = home.create("Duke DeEarl", "123");

4)我们可以掉用Cart对象的方法了(但是他调用的其实是CartBean里面对应的方法)

shoppingCart.addBook("The Martian Chronicles");


有点神奇哟,一定是Sun所说的什么EJB Container在暗中作了什么手脚.


 
 类似资料: