Feng.Li's Java See

          抓緊時間,大步向前。
          隨筆 - 95, 文章 - 4, 評論 - 58, 引用 - 0
          數據加載中……

          EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)

          1:安裝Jboss.不需要設置classpath,直接安裝就好了。

          2:EJB源文件:InterestCalculator.java( 遠程接口)
          package ejb;

          // Java core libraries
          import java.rmi.RemoteException;

          // Java standard extensions
          import javax.ejb.EJBObject;

          public interface InterestCalculator extends EJBObject {
            
             // set principal amount
             public void setPrincipal( double amount )
                throws RemoteException;
            
             // set interest rate
             public void setInterestRate( double rate )
                throws RemoteException;
            
             // set loan length in years
             public void setTerm( int years )
                throws RemoteException;
            
             // get loan balance
             public double getBalance() throws RemoteException;
            
             // get amount of interest earned
             public double getInterestEarned() throws RemoteException;  
          }
          2: InterestCalculatorHome.java(本地接口)
          package ejb;

          // Java core libraries
          import java.rmi.RemoteException;

          // Java standard extensions
          import javax.ejb.*;

          public interface InterestCalculatorHome extends EJBHome {
            
             // create InterestCalculator EJB
             public InterestCalculator create() throws RemoteException,
                CreateException;
          }
          3: InterestCalculatorBean .java(EJB的Bean文件,核心)

          package ejb;

          // Java core libraries
          import java.util.*;

          // Java standard extensions
          import javax.ejb.*;

          public class InterestCalculatorBean implements SessionBean {
            
             private SessionContext sessionContext;
            
             // state variables
             private double principal;
             private double interestRate;
             private int term;  
            
             // set principal amount
             public void setPrincipal( double amount )
             {
                principal = amount;
             }
            
             // set interest rate
             public void setInterestRate( double rate )
             {
                interestRate = rate;
             }
            
             // set loan length in years
             public void setTerm( int years )
             {
                term = years;
             }
            
             // get loan balance
             public double getBalance()
             {
                // calculate simple interest
                return principal * Math.pow( 1.0 + interestRate, term );
             }
            
             // get amount of interest earned
             public double getInterestEarned()
             {
                return getBalance() - principal;
             }
            
             // set SessionContext
             public void setSessionContext( SessionContext context )
             {
                sessionContext = context;
             }
            
             // create InterestCalculator instance
             public void ejbCreate() {}
            
             // remove InterestCalculator instance
             public void ejbRemove() {}  

             // passivate InterestCalculator instance
             public void ejbPassivate() {}
            
             // activate InterestCalculator instance
             public void ejbActivate() {}
          }

          4:EJB客戶端(注意: env.put(Context.PROVIDER_URL, "127.0.0.1:1099");
          )1099端口為jboss下運行Jndi服務的端口,這個不能錯,我就是掛在這了。
          package client;

          // Java core libraries
          import java.awt.*;
          import java.awt.event.*;
          import java.rmi.*;
          import java.text.*;
          import java.util.*;

          // Java standard extensions
          import javax.swing.*;
          import javax.rmi.*;
          import javax.naming.*;
          import javax.ejb.*;

          // Deitel libraries
          import ejb.*;

          public class InterestCalculatorClient extends JFrame {
            
             // InterestCalculator remote reference
             private InterestCalculator calculator;
            
             private JTextField principalTextField;
             private JTextField rateTextField;
             private JTextField termTextField;
             private JTextField balanceTextField;
             private JTextField interestEarnedTextField;
               
             // InterestCalculatorClient constructor
             public InterestCalculatorClient()
             {    
                super( "Stateful Session EJB Example" );   
               
                // create InterestCalculator for calculating interest
                createInterestCalculator();
               
                // create JTextField for entering principal amount
                createPrincipalTextField();
               
                // create JTextField for entering interest rate
                createRateTextField();

                // create JTextField for entering loan term
                createTermTextField();
               
                // create uneditable JTextFields for displaying balance
                // and interest earned
                balanceTextField = new JTextField( 10 );
                balanceTextField.setEditable( false );     
               
                interestEarnedTextField = new JTextField( 10 );
                interestEarnedTextField.setEditable( false );
               
                // layout components for GUI
                layoutGUI();
               
                // add WindowListener to remove EJB instances when user
                // closes window
                addWindowListener( getWindowListener() );
               
                setSize( 425, 200 );
                setVisible( true );
               
             } // end InterestCalculatorClient constructor
            
             // create InterestCalculator EJB instance
             public void createInterestCalculator()
             {
                // lookup InterestCalculatorHome and create
                // InterestCalculator EJB
                try {
                  Hashtable env = new Hashtable();
                   env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
                env.put(Context.PROVIDER_URL, "127.0.0.1:1099");
                   InitialContext initialContext = new InitialContext(env);
                  
                   // lookup InterestCalculator EJB
                   Object homeObject =
                      initialContext.lookup( "InterestCalculator" );
                  
                   // get InterestCalculatorHome interface
                   InterestCalculatorHome calculatorHome =
                      ( InterestCalculatorHome )
                         PortableRemoteObject.narrow( homeObject,
                            InterestCalculatorHome.class );        
                  
                   // create InterestCalculator EJB instance
                   calculator = calculatorHome.create();
                  
                } // end try
               
                // handle exception if InterestCalculator EJB not found
                catch ( NamingException namingException ) {
                   namingException.printStackTrace();
                }
               
                // handle exception when creating InterestCalculator EJB
                catch ( RemoteException remoteException ) {
                   remoteException.printStackTrace();
                }
               
                // handle exception when creating InterestCalculator EJB
                catch ( CreateException createException ) {
                   createException.printStackTrace();
                }           
             } // end method createInterestCalculator
            
             // create JTextField for entering principal amount
             public void createPrincipalTextField()
             {
                principalTextField = new JTextField( 10 );
               
                principalTextField.addActionListener(
                   new ActionListener() {
                     
                      public void actionPerformed( ActionEvent event )
                      {
                         // set principal amount in InterestCalculator
                         try {
                            double principal = Double.parseDouble(
                               principalTextField.getText() );

                            calculator.setPrincipal( principal );
                         }

                         // handle exception setting principal amount
                         catch ( RemoteException remoteException ) {
                            remoteException.printStackTrace();
                         }
                        
                         // handle wrong number format
                         catch ( NumberFormatException
                            numberFormatException ) {
                            numberFormatException.printStackTrace();
                         }
                      }
                   }
                ); // end addActionListener     
             } // end method createPrincipalTextField  
            
             // create JTextField for entering interest rate
             public void createRateTextField()
             {
                rateTextField = new JTextField( 10 );
               
                rateTextField.addActionListener(
                   new ActionListener() {
                     
                      public void actionPerformed( ActionEvent event )
                      {
                         // set interest rate in InterestCalculator
                         try {
                            double rate = Double.parseDouble(
                               rateTextField.getText() );

                            // convert from percentage
                            calculator.setInterestRate( rate / 100.0 );
                         }

                         // handle exception when setting interest rate
                         catch ( RemoteException remoteException ) {
                            remoteException.printStackTrace();
                         }           
                      }
                   }
                ); // end addActionListener           
             } // end method createRateTextField  
            
             // create JTextField for entering loan term
             public void createTermTextField()
             {
                termTextField = new JTextField( 10 );
               
                termTextField.addActionListener(
                   new ActionListener() {
                     
                      public void actionPerformed( ActionEvent event )
                      {
                         // set loan term in InterestCalculator
                         try {
                            int term = Integer.parseInt(
                               termTextField.getText() );

                            calculator.setTerm( term );
                         }

                         // handle exception when setting loan term
                         catch ( RemoteException remoteException ) {
                            remoteException.printStackTrace();
                         }           
                      }
                   }
                ); // end addActionListener     
             } // end method getTermTextField  
            
             // get JButton for starting calculation
             public JButton getCalculateButton()
             {
                JButton calculateButton = new JButton( "Calculate" );
               
                calculateButton.addActionListener(
                   new ActionListener() {
                     
                      public void actionPerformed( ActionEvent event )
                      {
                         // use InterestCalculator to calculate interest
                         try {

                            // get balance and interest earned
                            double balance = calculator.getBalance();
                            double interest =
                               calculator.getInterestEarned();

                            NumberFormat dollarFormatter =
                               NumberFormat.getCurrencyInstance(
                                  Locale.US );

                            balanceTextField.setText(
                               dollarFormatter.format( balance ) );

                            interestEarnedTextField.setText(
                               dollarFormatter.format( interest ) );
                         }

                         // handle exception when calculating interest
                         catch ( RemoteException remoteException ) {
                            remoteException.printStackTrace();
                         }
                      } // end method actionPerformed
                   }
                ); // end addActionListener
               
                return calculateButton;
               
             } // end method getCalculateButton
            
             // lay out GUI components in JFrame
             public void layoutGUI()
             {
                Container contentPane = getContentPane();
               
                // layout user interface components
                JPanel inputPanel = new JPanel( new GridLayout( 5, 2 ) );
               
                inputPanel.add( new JLabel( "Principal" ) );
                inputPanel.add( principalTextField );
               
                inputPanel.add( new JLabel( "Interest Rate (%)" ) );
                inputPanel.add( rateTextField );
               
                inputPanel.add( new JLabel( "Term (years)" ) );
                inputPanel.add( termTextField );
               
                inputPanel.add( new JLabel( "Balance" ) );
                inputPanel.add( balanceTextField );
               
                inputPanel.add( new JLabel( "Interest Earned" ) );
                inputPanel.add( interestEarnedTextField );     
               
                // add inputPanel to contentPane
                contentPane.add( inputPanel, BorderLayout.CENTER );
               
                // create JPanel for calculateButton
                JPanel controlPanel = new JPanel( new FlowLayout() );
                controlPanel.add( getCalculateButton() );
                contentPane.add( controlPanel, BorderLayout.SOUTH );
             }
            
             // get WindowListener for exiting application
             public WindowListener getWindowListener()
             {
                return new WindowAdapter() {
                     
                   public void windowClosing( WindowEvent event )
                   {
                      // check to see if calculator is null
                      if ( calculator.equals( null ) ) {
                         System.exit( -1 );
                      }
                     
                      else {
                         // remove InterestCalculator instance
                         try {
                            calculator.remove();
                         }

                         // handle exception removing InterestCalculator
                         catch ( RemoveException removeException ) {
                            removeException.printStackTrace();
                            System.exit( -1 );
                         }

                         // handle exception removing InterestCalculator
                         catch ( RemoteException remoteException ) {
                            remoteException.printStackTrace();
                            System.exit( -1 );
                         }
                     
                         System.exit( 0 );
                      }
                   }
                };
             } // end method getWindowListener
            
             // execute the application
             public static void main( String[] args )
             {
                new InterestCalculatorClient();
             }
          }
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "<ejb-jar>
            <display-name>InterestCalculator</display-name>
            <enterprise-beans>
             <session>
              <display-name>InterestCalculator</display-name>
              <ejb-name>InterestCalculator</ejb-name>
              <home>ejb.InterestCalculatorHome</home>
              <remote>ejb.InterestCalculator</remote>
              <ejb-class>ejb.InterestCalculatorBean</ejb-class>
              <session-type>Stateless</session-type>
              <transaction-type>Bean</transaction-type>
             </session>
            </enterprise-beans>
          </ejb-jar>


          Jboss.xml文件現在暫時不需要,因為我們只是測試EJB的運行,而Jboss.xml這個文件是用來配置服務器的一些選項。

          jar  cvf TestEjb.jar ejb META-INF
          再把TestEjb.jar考至Deploy目錄下,Jboss支持熱部署。
          運行客戶端,。。。。。。。

          posted on 2006-11-02 19:04 小鋒 閱讀(2163) 評論(8)  編輯  收藏 所屬分類: J2EE

          評論

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          網上有一本EJB3.0實例的書,可以參考著學習,可以避免走彎路。其實要實現一個Session Bean及其客戶端還是十分簡單的,如果能充分利用Java 5.0引入的新特性,可以更好實現EJB程序。關于EJB 3.0的學習,可以結合著《EJB3.0實例》和《Mastering Enterprise Java Bean 3.0》這兩本書,前者比較注重實踐、后者對理論部分描述的比較多。
          2006-11-02 20:00 | lotusswan

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          踩個腳印
          2006-11-02 21:22 | 壞男孩

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          挺好,寫一個ejb 2.1的bean就知道它為什么要被取代了,不寫不知道麻煩。
          這些工作其實都是為了分布式部署,遠程調用,可是我們需要么?
          所以有了EJB 3.0……
          robbin好像寫過一個ejb 2.x的原理性的分析,可以結合這個例子分析。
          2006-11-02 23:07 | Tin

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          還是用3.0吧~~~~~看這程序的代碼數量就頭大了
          2006-11-03 08:44 | 展昭

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          ejb還能干什么??
          傳說中的ejb啊
          2006-11-03 09:13 | inlife.cn

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          老大,你這個是Stateless Session Bean呢!有沒有CMP的實體Bean實例啊!!!我掛在這里了,進行不下去了!!!郁悶!!!
          2006-11-03 11:43 | e_ville

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          實體Bean是吧,一樣的,注意下端口啊
          env.put(Context.PROVIDER_URL, "127.0.0.1:1099"); JBoss
          env.put(Context.PROVIDER_URL, "127.0.0.1:7001"); weblogic
          env.put(Context.PROVIDER_URL, "127.0.0.1:2809"); websphere

          同時,工廠類也需要注意:
          org.jnp.interfaces.NamingContextFactory JBoss
          weblogic.jndi.WLInitialContextFactory weblogic
          websphere我沒用過,不曉得。。。。

          你注意上面2個細節,要是還有問題,再來問我吧
          2006-11-03 17:49 | 小鋒

          # re: EJB的示例(希望那些和我一樣曾經被跑一個EJB難住的朋友不再走彎道)  回復  更多評論   

          EJB3.0吧,2.0的太多垃圾代碼了,不符合流行的POJO
          2006-11-04 17:10 | itVincent
          主站蜘蛛池模板: 平武县| 郓城县| 阳新县| 军事| 辉县市| 康保县| 长乐市| 呼伦贝尔市| 曲松县| 和静县| 兴山县| 五原县| 安平县| 三门县| 民丰县| 新乡县| 博客| 安义县| 淮北市| 米脂县| 屯留县| 明光市| 疏附县| 天津市| 哈尔滨市| 永福县| 靖边县| 泸水县| 沙河市| 沂南县| 比如县| 宜州市| 广元市| 景德镇市| 沙河市| 长武县| 凤山县| 当涂县| 五峰| 武宣县| 长汀县|