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" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<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 小锋 阅读(2155) 评论(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

只有注册用户登录后才能发表评论。


网站导航: