Study EJB (1)

来源:互联网 发布:通达信 数据引用公式 编辑:程序博客网 时间:2024/06/16 04:13

Study EJB 1

刚开始学习EJB , 这些例子是从<java2 技术内幕中扒下来>中扒下来。

以一个例子为开始:HelloWorld

写一个EJB的步骤:

1.     声明远程接口

public interface HelloWorld extends EJBObject

{

      public String sayHello(String words) throws RemoteException;

}

2.     添加工厂

2.public interface HelloWorldHome extends EJBHome

{

      public HelloWorld create() throws CreateExceptio , RemoteException;

}

3.     实现bean

public class HelloWorldBean implements SessionBean

   {

           //接口中的方法

           public void ejbActivate(){}

           public void ejbRemove() {}

           public void ejbPassivate() {}

           public void setSessionContext( SessionContext ctx) {}

           public void ejbCreate() throws CreateException {}

           //以下是要完成接口HelloWorld 中的业务方法

           public String sayHello(String words) throws RemoteException

{

System.out.println(“liuyd say to everybody”+words);

                      return words;

}

}

4.     对类进行编译

5.     编写 EJB 部署说明文件

<?xml version="1.0" ?>

  <!DOCTYPE ejb-jar (View Source for full doctype...)>

- <ejb-jar>

- <enterprise-beans>

- <session>

  <ejb-name>HelloWorld</ejb-name>

  <home> HelloWorldHome</home>

  <remote> HelloWorld</remote>

  <ejb-class> HelloWorldBean</ejb-class>

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

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

  </session>

  </enterprise-beans>

  </ejb-jar>

 

6.     Bean打包(包括所有类、部署文件)

7.     产生EJB容器代码(EJB容器自己完成对文件在EJB中的部署)

8.     部署EJB

9.     编写客户端

public class SimpleEJBClient

{

        private static final String JNDI_NAME = "HelloWorld";

        public static void main(String[] args)

        throws Exception

        {

     try                

{

                //jndi properties

                Properties h = new Properties();

              h.put(Context.INITIAL_CONTEXT_FACTORY,

                "weblogic.jndi.WLInitialContextFactory");

              h.put(Context.PROVIDER_URL,

                "t3://localhost:7001");

               //lookup jndi initial context

                InitialContext ctx = new InitialContext(h);

                //lookup home

                Object obj = ctx.lookup(JNDI_NAME);

//cast home

HelloWorldHome          home =(HelloWorldHome)PortableRemoteObject.narrow(obj, elloWorldHome.class);

        //create the bean

        Object ejbObj = home.create();

        //cast the bean to our interface

        HelloWorld simpleEJB =           (HelloWorld)PortableRemoteObject.narrow(ejbObj, HelloWorld.class);

        /call bean's method

        System.out.println("Calling Simple EJB: " + simpleEJB.sayIt());

        }

catch (Exception e)

        {

             System.out.println(e.getMessage());

                e.printStackTrace();

    }       

       }

}