第一步:建立工程選擇【File】-〉【New Project】,出現下面的介面:選擇【Enterprise】-〉【Enterprise Application Client】,進入下面的介面:輸入工程的名字:HelloClient,點擊完成即可。
第二步:使用EJB的介面建立一個包在HelloClient應用的【Source Package】上建立一個Java包,包名為session.home,與要訪問的EJB的包名相同。
把介面檔案拷貝過來然後選擇EJB應用中的檔案:HelloSessionRemote.java,點擊右鍵,選擇【copy】然後選擇HelloClient應用的【session.home】介面,點擊右鍵,選擇【paste】
第三步:修改用戶端的代碼系統自動產生的類檔案的代碼如下:/* * Main.java * * Created on 2007年4月19日, 下午7:51 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package helloclient; /** * * @author Administrator */public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
使用注入的方式訪問EJB注入EJB,代碼如下: @EJBprivate static HelloSessionRemote hello; 需要匯入EJB和HelloSessionRemote,代碼如下:import javax.ejb.EJB;import session.hello.*; 編寫測試代碼,代碼如下: public void test(){ System.out.println(hello.hello()); } 在main方法中調用測試方法,代碼如下: public static void main(String[] args) { Main m = new Main(); m.test(); } 完整的代碼如下:/* * Main.java * * Created on 2007年4月19日, 下午7:51 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package helloclient;import javax.ejb.EJB;import session.hello.*; /** * * @author Administrator */public class Main { // @EJB private static HelloSessionRemote hello; /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { Main m = new Main(); m.test(); } public void test(){ System.out.println("result:"+hello.hello()); }} 選擇工程,點擊右鍵,選擇“Run Project”。運行結果如下:
使用JNDI查詢的方式訪問EJB定義一個成員變數:private static HelloSessionRemote hello; 添加一個查詢EJB的初始化方法 public void init(){ try{ Context ctx = new InitialContext(); hello =(HelloSessionRemote) ctx.lookup(HelloSessionRemote.class.getName()); }catch(Exception e){ System.out.println(e.toString()); } } 在構造方法中添加對init方法的調用 public Main() { init();} 需要匯入的包:import javax.ejb.EJB;import session.hello.*;import javax.naming.*; // 這是與前面不同的地方 測試方法和main方法都不變。 選擇工程,點擊右鍵,選擇“Run Project”。運行結果與上面的啟動並執行結果相同。
參考書:《Java EE 5實用教程——基於WebLogic和Eclipse》EJB部分