在一个ejb中使用别的ejb跟在客户端使用区别不大。
travelagentbean使用了四个entity bean和一个无状态session bean,代码如下:
package com.titan.travelagent;import com.titan.cabin.*;
import com.titan.cruise.*;
import com.titan.customer.*;
import com.titan.processpayment.*;
import com.titan.reservation.*;import java.sql.*;
import javax.sql.DataSource;
import java.util.Vector;
import java.rmi.RemoteException;
import javax.naming.NamingException;
import javax.ejb.EJBException;
public class TravelAgentBean implements javax.ejb.SessionBean {    public Customer customer;
    public Cruise cruise;
    public Cabin cabin;    public javax.ejb.SessionContext ejbContext;
    public javax.naming.Context jndiContext;    public void ejbCreate(Customer cust){
        customer = cust;
    }
    public int getCustomerID( )
    throws IncompleteConversationalState{
        try{
            if(customer == null)
                throw new IncompleteConversationalState();
            return ((CustomerPK)customer.getPrimaryKey()).id;
        }catch(RemoteException re){
            throw new EJBException(re);
        }
    }
    public int getCruiseID( )
    throws IncompleteConversationalState{
        try{
            if(cruise == null)
                throw new IncompleteConversationalState();
            return ((CruisePK)cruise.getPrimaryKey()).id;
        }catch(RemoteException re){
            throw new EJBException(re);
        }
        
    }
        
    public int getCabinID( )
    throws IncompleteConversationalState{
        try{
            if(cabin==null)
                throw new IncompleteConversationalState();
            return ((CabinPK)cabin.getPrimaryKey()).id;
        }catch(RemoteException re){
            throw new EJBException(re);
        }
    }
    public void setCabinID(int cabinID)
    throws javax.ejb.FinderException{
        try{
            CabinHome home = (CabinHome)getHome("CabinBean",CabinHome.class);
            CabinPK pk = new CabinPK();
            pk.id=cabinID;
            cabin = home.findByPrimaryKey(pk);
        }catch(RemoteException re){
            throw new EJBException(re);
        }
    }
    public void setCruiseID(int cruiseID)
    throws javax.ejb.FinderException{
        try{
            CruiseHome home = (CruiseHome)getHome("CruiseBean", CruiseHome.class);
            cruise = home.findByPrimaryKey(new CruisePK(cruiseID));
        }catch(RemoteException re){
            throw new EJBException(re);
        }
        
    }
    public Ticket bookPassage(CreditCard card, double price)
    throws IncompleteConversationalState{
                            if(customer == null || cruise == null || cabin == null){
            throw new IncompleteConversationalState();
        }
        try{
            ReservationHome resHome =
                (ReservationHome) getHome("ReservationBean",ReservationHome.class);
            Reservation reservation =
            resHome.create(customer, cruise, cabin,price);
            ProcessPaymentHome ppHome =
                (ProcessPaymentHome) getHome("ProcessPaymentBean",ProcessPaymentHome.class);
            ProcessPayment process = ppHome.create();
            process.byCredit(customer, card, price);            Ticket ticket = new Ticket(customer,cruise,cabin,price);
            return ticket;
        }catch(Exception e){
            throw new EJBException(e);
        }
    }
    public void ejbRemove(){}
    public void ejbActivate(){}
    public void ejbPassivate(){}    public void setSessionContext(javax.ejb.SessionContext cntx){
        ejbContext = cntx;
        try{
          jndiContext = new javax.naming.InitialContext();
        }catch(NamingException ne){
            throw new EJBException(ne);
        }
    }
    protected Object getHome(String name,Class type){
        try{
            Object ref = jndiContext.lookup("java:comp/env/ejb/"+name);
            return javax.rmi.PortableRemoteObject.narrow(ref, type);
        }catch(NamingException ne){
            throw new EJBException(ne);
        }
    }
    private Connection getConnection() throws SQLException{
        try{
           DataSource ds = (DataSource)jndiContext.lookup("java:comp/env/jdbc/mssqlPool");
           return ds.getConnection( );
        }catch(NamingException ne){throw new EJBException(ne);}
    }
    public String [] listAvailableCabins(int bedCount)
    throws IncompleteConversationalState{        if(cruise == null) throw new IncompleteConversationalState();
        Connection con = null;
        PreparedStatement ps = null;;
        ResultSet result = null;
        try {
            int cruiseID = ((CruisePK)cruise.getPrimaryKey()).id;
            int shipID = cruise.getShipID();
            con = getConnection();
            ps = con.prepareStatement(
                "select ID, NAME, DECK_LEVEL  from CABIN "+
                "where SHIP_ID = ? and ID NOT IN "+
                "(SELECT CABIN_ID FROM RESERVATION WHERE CRUISE_ID = ?)");            ps.setInt(1,shipID);
            ps.setInt(2,cruiseID);
            result = ps.executeQuery();
            Vector vect = new Vector();
            while(result.next()){
                StringBuffer buf = new StringBuffer();
                buf.append(result.getString(1));
                buf.append(',');
                buf.append(result.getString(2));
                buf.append(',');
                buf.append(result.getString(3));
                vect.addElement(buf.toString());
            }
            String [] returnArray = new String[vect.size()];
            vect.copyInto(returnArray);
            return returnArray;
        }
        catch (Exception e) {
            throw new EJBException(e);
        }
        finally {
            try {
                if (result != null) result.close();
                if (ps != null) ps.close();
                if (con!= null) con.close();
            }catch(SQLException se){se.printStackTrace();}
        }
    }
}

解决方案 »

  1.   

    Object ref = jndiContext.lookup("java:comp/env/ejb/"+name);
    请问这个name是不是就是配置资源是的名字?            
      

  2.   

    对不起,还有一个很小的问题,hehe
    是不是同在服务器短的东西
    jndiContext = new javax.naming.InitialContext();这样就可以了
    要是不在服务器上的客户端
    就需要传一个HashTable作为参数给他?
      

  3.   

    对,
    java:comp/env/是所有环境变量的前缀
    后面跟上在部署工具中设置的reference名 ,如ejb/xxxx
    合起来就是java:comp/env/ejb/xxxx
      

  4.   

    奇怪,刚才写的贴字怎么都没有了,在写一遍吧
    Object ref = jndiContext.lookup("java:comp/env/ejb/"+name);
    这个name是不是就是delpoy是的资源的名字?
    在服务器端运行的程序只需要
    jndiContext = new javax.naming.InitialContext();
    就可以了
    如若是客户端,即程序不是在服务器端运行,是不是就要给一个HashTable的参数给他?
    这么说对不对呀?        
      

  5.   

    to darcy07:
    你的意思是说客户端也可以直接用
    jndiContext = new javax.naming.InitialContext()
    吗?
      

  6.   

    是啊,不过对于standalone client不能好象访问java:comp/env变量
      

  7.   

    to acool
    可以在客户端直接使用.
      

  8.   

    CabinHome home = (CabinHome)getHome("CabinBean",CabinHome.class);
    这句调用getHome函数
    name即"CabinBean"
    在这时
    Object ref = jndiContext.lookup("java:comp/env/ejb/"+name);
    就是
    Object ref = jndiContext.lookup("java:comp/env/ejb/CabinBean");当资源在同一服务器上,jndiContext = new javax.naming.InitialContext()
    就行了。
    客户端这样使用不行,不同的服务器不一样
    weblogic的应该这样写
        Context jndiContext = getWeblogicInitialContext();
        public static Context getWeblogicInitialContext() 
                              throws javax.naming.NamingException {
           Properties p = new Properties();
           p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
           p.put(Context.PROVIDER_URL, "t3://localhost:7001");
           return new InitialContext(p);
        }你没仔细看吧?这个bean很说明问题的
      

  9.   

    to:backlove(我愿意) 
    能不能把你的qq或者email留下呀?
      

  10.   

    我也不怎么的,互相学习吧
    [email protected]