EJB入門例子

 該文章在<<EJB編程指南>>的實例的基礎上建立的,主要是給新手一個比較直觀的例子和作爲自己的日誌,並不打算介紹EJB的原理性的東西。另外,由於本人水平有限,請不吝賜教。
      筆者使用的IDE爲:Eclipse3.0+MyEclipse4.01GA
      J2EE容器爲:JBoss4.0
   
      本文描述一個幫助存款和取款的無狀態會話Bean的完整開發及部署的過程。步驟如下:
1、編寫無狀態會話Bean的實現類。
2、編寫無狀態會話Bean的主接口和組件接口。
3、將Bean彙編成應用程序,編寫部署描述項。
4、在EJB服務器上部署應用程序。
5、用Java應用程序進行測試。
上面是主要的過程,有些步驟可以不用手工完成,通過IDE可以簡化開發過程,如果你對IDE的該功能不太清楚可以參考產品文檔(http: //myeclipseide.com/enterpriseworkbench/help/index.jsp?topic=/com.genuitec.myeclipse.doc/html/quickstarts/firstejb/index.html)。

一、新建一個EJB Project,工程名字爲FundEJB,其他默認就好。
二、創建Session Bean:
      1、在src目錄下新建包:qiya.deng.fund.ejb,請注意包名最後一定要以ejb爲後綴,因爲後面我們需要使用的XDoclet工具。
      2、新建SessionBean class,命名爲StatelessFundManagerEJB,要需要以EJB爲後綴,原因同上,而且根據規範最好是以EJB或是Bean爲後綴。

      3、配置XDoclet :
      右擊項目選擇Properties,選擇MyEclipse-XDoclet,點擊Add Stander...,選擇Standard EJB。
      選中Standard EJB,在ejbxdoclet上點擊右鍵添加Add,在其中選擇jboss,因爲該例子中使用jboss作爲應用服務器。選中jboss,修改下列屬性
      Version = 4.0
      destDir = src/META-INF
     修改完畢,點擊OK按鈕回到主窗口。

      4、運行Xdoclet:
      右擊項目選擇MyEclipse->run Xdoclet。運行是console窗口會產生提示信息,運行完畢可以看到目錄結構發生變化。
      5、編輯實現類StatelessFundManagerEJB:
      在編輯StatelessFundManagerEJB類之前選觀察下StatelessFundManager接口,一定可以發現這個遠程組件接口的接口方法和StatelessFundManager的方法是有對應關係的。
      在StatelessFundManager.java文件最後添加:


          /**
       *
       * @param balance
       * @param amount
       * @return
       *
       * @ejb.interface-method
       */
      public double addFunds(double balance,double amount){
          balance += amount;
          return balance;
      }
    
      /**
       *
       * @param balance
       * @param amount
       * @return
       * @throws InsufficientBalanceException
       *
       * @ejb.interface-method
       */
      public double withdrawFunds(double balance,double amount)throws InsufficientBalanceException {
          if (balance < amount) {
              throw (new InsufficientBalanceException());
          }
          balance -= amount;
          return balance;
      }

      重複第4步運行Xdoclet,之後觀察StatelessFundManager接口。

     6、部署該應用到EJB服務器:
      部署描述項在IDE自動生成了,該文件的位置在/META-INF/ejb-jar.xml。打開ejb-jar.xml,jboss.xml文件描述進行查看。
      利用MyEclipse提供的部署工具進行部署:
      然後運行JBoss容器,可以看到有如下信息提示:
      關於MyEclipse中Application Server的使用請查看文檔(http://www.myeclipseide.com/images/tutorials/quickstarts/appservers/)。
      到現在爲止,你已經發布了一個簡單的無狀態的會話Bean。下面寫個簡單的應用程序進行測試.
    
三、編寫進行測試的Java客戶端程序。
      客戶端程序可以是Web程序也可以是Application應用程序。這裏以Application應用程序爲例。
      同樣使用Eclipse,新建Java Project,這裏命名爲FundClient。右擊該項目選擇properties->Java Build path,在Projects中加入上面的Project:FundEJB。在Libraries中點擊Add External JARs...,把$JBoss_Home/client的目錄下的所有jar文件添加到Libraries中。
      最後,就是編寫客戶端代碼:
package qiya.deng.client;
      //import省去
public class StatelessFundManagerTestClient extends JFrame implements
          ActionListener {

      double balance = 0;
      JTextField amount = new JTextField(10);
      JButton addFunds = new JButton("Add Funds");
      JButton withdrawFunds = new JButton("Withdraw Funds");
      String msg = "Current account balance";
      String strBal = "0";
      JLabel status;
      StatelessFundManager manager;
      NumberFormat currencyFormatter;
    
      public StatelessFundManagerTestClient(){
          super("Fund Manager");
      }
    
      public static void main(String[] args){
          new StatelessFundManagerTestClient().init();
      }
    
      private void init() {
        
          buildGUI();
        
          addWindowListener(new WindowAdapter(){
              public void windowClosing(WindowEvent event){
                  System.exit(0);
              }
          });
        
          addFunds.addActionListener(this);
          withdrawFunds.addActionListener(this);
        
          createFundManager();
        
          currencyFormatter = NumberFormat.getCurrencyInstance();
          String currencyOut = currencyFormatter.format(0);
          status.setText(msg + currencyOut);
        
          pack();
          show();
      }

      private void buildGUI() {
          GridBagLayout gl = new GridBagLayout();
          GridBagConstraints gc = new GridBagConstraints();
          Container container = getContentPane();
          container.setLayout(gl);
        
          gc.fill = GridBagConstraints.BOTH;
          JLabel label = new JLabel("Enter Amount");
          gl.setConstraints(label,gc);
          container.add(label);
        
          gc.gridwidth = GridBagConstraints.REMAINDER;
          gl.setConstraints(amount,gc);
          container.add(amount);
        
          gl.setConstraints(addFunds,gc);
          container.add(addFunds);
          gl.setConstraints(withdrawFunds,gc);
          container.add(withdrawFunds);
        
          status = new JLabel(msg);
          gl.setConstraints(status,gc);
          container.add(status);
      }

      public void createFundManager(){
          try {
              Properties prop = new Properties();
              prop.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
              prop.put(Context.PROVIDER_URL,"localhost:1099");
              Context initial = new InitialContext(prop);
              Object objref = initial.lookup("ejb/StatelessFundManager");//JINI-Name
              StatelessFundManagerHome home =
                  (StatelessFundManagerHome) PortableRemoteObject.narrow(objref,StatelessFundManagerHome.class);
              manager = home.create();
          } catch (ClassCastException e) {
              e.printStackTrace();
          } catch (RemoteException e) {
              e.printStackTrace();
          } catch (NamingException e) {
              e.printStackTrace();
          } catch (CreateException e) {
              e.printStackTrace();
          }
      }

      public void actionPerformed(ActionEvent e) {
          if (e.getActionCommand().equalsIgnoreCase("Withdraw Funds")) {
              System.out.println("Withdraw Funds");
          }
          if (e.getActionCommand().equalsIgnoreCase("Add Funds")) {
              System.out.println("Add Funds");
          }
        
          if (e.getSource().equals(addFunds)){
              System.out.println("addFunds");
              try {
                  status.setText(msg + currencyFormatter.format(manager.addFunds(0,Double.parseDouble(amount.getText()))));
              } catch (NumberFormatException e1) {
                  e1.printStackTrace();
              } catch (RemoteException e1) {
                  e1.printStackTrace();
              }
          }
          if (e.getSource().equals(withdrawFunds)){
              System.out.println("withdrawFund");
              try {
                  status.setText(msg + currencyFormatter.format(manager.withdrawFunds(100,Double.parseDouble(amount.getText()))));
              } catch (NumberFormatException e1) {
                  e1.printStackTrace();
              } catch (RemoteException e1) {
                  e1.printStackTrace();
              } catch (InsufficientBalanceException e1) {
                  e1.printStackTrace();
              }
          }
      }
}
      然後,你可以運行該程序進行測試了:    
      至此,恭喜你,你已經大功告成,基本上對EJB建立了感性的認識,可以參考資料進行深入的學習了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章