EJB創(chuàng)建應(yīng)用程序

2018-12-07 17:26 更新

要創(chuàng)建一個簡單的EJB模塊,我們將使用NetBeans“新建項目”向?qū)?。在下面的例子中,我們將?chuàng)建一個名為Component的EJB模塊項目。

創(chuàng)建項目

在NetBeans IDE中,選擇文件>新建項目>(File > New Project >)。你會看到以下畫面。


新建項目


在項目類別中選擇項目類型,Java EE中 ,項目類型為EJB模塊 。單擊下一步>(Next >按鈕。你會看到以下畫面。


EJB模塊

輸入項目名稱和位置。單擊下一步>Next >按鈕。你會看到以下畫面。


輸入項目名稱和位置


選擇下圖中選項作為JBoss應(yīng)用服務(wù)器 。單擊Finish按鈕。你會看到NetBeans中創(chuàng)建以下項目。


項目資源管理器

創(chuàng)建示例EJB

要創(chuàng)建一個簡單的EJB,我們將使用NetBeans“新建”向?qū)АT谙旅娴睦又?,我們將?chuàng)建EjbComponent項目名為librarySessionBean的一個無狀態(tài)的EJB類。


選擇項目EjbComponent在項目資源管理器窗口,并在其上單擊右鍵。選擇New > Session Bean
,
即可看到新的Bean向?qū)?/span>會話。


新建會話Bean向?qū)? style=

輸入會話bean名稱和包名稱。單擊Finish按鈕。你會看到NetBeans中創(chuàng)建以下EJB類。


  • LibrarySessionBean -無狀態(tài)會話bean

  • LibrarySessionBeanLocal -本地接口的會話bean


我改變本地接口的遠程接口,我們要訪問我們的EJB在控制臺基礎(chǔ)的應(yīng)用。遠程/本地接口用于公開,一個EJB必須實現(xiàn)業(yè)務(wù)方法。


LibrarySessionBeanLocal被重命名為LibrarySessionBeanRemote和LibrarySessionBean實現(xiàn)LibrarySessionBeanRemote接口。


LibrarySessionBeanRemote

package com.tutorialspoint.stateless;
 
import java.util.List;
import javax.ejb.Remote;
 
@Remote
public interface LibrarySessionBeanRemote {
 
    void addBook(String bookName);
 
    List getBooks();
    
}


LibrarySessionBean

package com.tutorialspoint.stateless;
 
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
 
@Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
    
    List<String> bookShelf;    
    
    public LibrarySessionBean(){
       bookShelf = new ArrayList<String>();
    }
    
    public void addBook(String bookName) {
        bookShelf.add(bookName);
    }    
 
    public List<String> getBooks() {
        return bookShelf;
    }
}


建設(shè)項目

  • 在項目資源管理器窗口中選擇Ejb組件(Component)項目

  • 右鍵點擊它,打開上下文菜單。

  • 選擇清理并生成。


你會看到在NetBeans控制臺輸出以下輸出。

ant -f C:EJBEjbComponent clean dist
init:
undeploy-clean:
deps-clean:
Deleting directory C:EJBEjbComponentuild
Deleting directory C:EJBEjbComponentdist
clean:
init:
deps-jar:
Created dir: C:EJBEjbComponentuildclasses
Copying 3 files to C:EJBEjbComponentuildclassesMETA-INF
Created dir: C:EJBEjbComponentuildempty
Created dir: C:EJBEjbComponentuildgenerated-sourcesap-source-output
Compiling 2 source files to C:EJBEjbComponentuildclasses
warning: [options] bootstrap class path not set in conjunction with -source 1.6
Note: C:EJBEjbComponentsrcjavacom	utorialspointstateless
LibraryPersistentBean.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 warning
compile:
library-inclusion-in-archive:
Created dir: C:EJBEjbComponentdist
Building jar: C:EJBEjbComponentdistEjbComponent.jar
dist:
BUILD SUCCESSFUL (total time: 3 seconds)


啟動應(yīng)用服務(wù)器

  • 在服務(wù)窗口服務(wù)器下選擇JBoss應(yīng)用服務(wù)器

  • 右鍵點擊它,打開上下文菜單。

  • 選擇啟動。


你會看到在NetBeans下JBoss應(yīng)用服務(wù)器下面的輸出,輸出。

Calling C:jboss-5.1.0.GAin
un.conf.bat
=========================================================================
 
  JBoss Bootstrap Environment
 
  JBOSS_HOME: C:jboss-5.1.0.GA
 
  JAVA: C:Program Files (x86)Javajdk1.6.0_21injava
 
  JAVA_OPTS: -Dprogram.name=run.bat -Xms128m -Xmx512m -server
 
  CLASSPATH: C:jboss-5.1.0.GAin
un.jar
 
=========================================================================
 
16:25:50,062 INFO  [ServerImpl] Starting JBoss (Microcontainer)...
16:25:50,062 INFO  [ServerImpl] Release ID: JBoss [The Oracle] 5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)
...
 
16:26:40,420 INFO  [TomcatDeployment] deploy, ctxPath=/admin-console
16:26:40,485 INFO  [config] Initializing Mojarra (1.2_12-b01-FCS) for context '/admin-console'
16:26:42,362 INFO  [TomcatDeployment] deploy, ctxPath=/
16:26:42,406 INFO  [TomcatDeployment] deploy, ctxPath=/jmx-console
16:26:42,471 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080
16:26:42,487 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009
16:26:42,493 INFO  [ServerImpl] JBoss (Microcontainer) [5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 52s:427ms


部署項目

  • 在項目資源管理器窗口中選擇Ejb組件(Component)項目

  • 右鍵點擊它,打開上下文菜單。

  • 選擇部署。


你會看到在NetBeans控制臺輸出以下輸出。

ant -f C:EJBEjbComponent -DforceRedeploy=true -Ddirectory.deployment.supported=false -Dnb.wait.for.caches=true run
init:
deps-jar:
compile:
library-inclusion-in-archive:
Building jar: C:EJBEjbComponentdistEjbComponent.jar
dist-directory-deploy:
pre-run-deploy:
Checking data source definitions for missing JDBC drivers...
Distributing C:EJBEjbComponentdistEjbComponent.jar to [org.jboss.deployment.spi.LocalhostTarget@1e4f84ee]
Deploying C:EJBEjbComponentdistEjbComponent.jar
Applicaton Deployed
Operation start started
Operation start completed
post-run-deploy:
run-deploy:
run:
BUILD SUCCESSFUL (total time: 2 seconds)


JBoss應(yīng)用服務(wù)器的日志輸出

16:30:00,963 INFO  [DeployHandler] Begin start, [EjbComponent.jar]
...
16:30:01,233 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-5.1.0.GA/server/default/deploy/EjbComponent.jar/}
...
16:30:01,281 INFO  [JBossASKernel]    jndi:LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO  [JBossASKernel]    Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO  [JBossASKernel]    jndi:LibrarySessionBean/remote
16:30:01,281 INFO  [JBossASKernel]  Added bean(jboss.j2ee:jar=EjbComponent.jar,name=
LibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar
16:30:01,282 INFO  [JBossASKernel] installing bean: jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3
16:30:01,282 INFO  [JBossASKernel]   with dependencies:
16:30:01,282 INFO  [JBossASKernel]   and demands:
16:30:01,282 INFO  [JBossASKernel]    jboss.ejb:service=EJBTimerService
...
16:30:01,283 INFO  [EJB3EndpointDeployer] Deploy AbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar, name=LibrarySessionBean, service=EJB3_endpoint bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImpl properties=[container] constructor=null autowireCandidate=true}
...
16:30:01,394 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:01,395 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
   LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
 
   LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
   LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
 


創(chuàng)建客戶端訪問EJB

  • 在NetBeans IDE中,選擇文件>新建項目>(File > New Project >)。

  • 在類別中選擇項目類型,Java ,項目類型為Java應(yīng)用程序 。單擊下一步>(Next >按鈕。

  • 輸入項目名稱和位置。單擊Finish>按鈕。我們選擇的名稱為EjbTester。

  • 右鍵點擊Project Explorer窗口中的項目名稱。選擇屬性(properties

  • 在早先創(chuàng)建EJB組件項目中添加使用編譯選項的添加項目按鈕。

  • 使用編譯選項中添加JAR /文件夾按鈕添加的JBoss庫。 Jboss的庫可以位于<JBoss安裝文件夾>>客戶端文件夾。


EjbTester中創(chuàng)建文件名為jndi.properties的項目。

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost


其下創(chuàng)建包com.tutorialspoint.test和EJBTester.java類。


EJBTester.java

package com.tutorialspoint.test;
 
import com.tutorialspoint.stateless.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
 
public class EJBTester {
 
   BufferedReader brConsoleReader = null; 
   Properties props;
   InitialContext ctx;
   {
      props = new Properties();
      try {
      props.load(new FileInputStream("jndi.properties"));
      } catch (IOException ex) {
      ex.printStackTrace();
      }
      try {
      ctx = new InitialContext(props);            
      } catch (NamingException ex) {
      ex.printStackTrace();
      }
      brConsoleReader = 
      new BufferedReader(new InputStreamReader(System.in));
   }
   public static void main(String[] args) {
 
      EJBTester ejbTester = new EJBTester();
 
      ejbTester.testStatelessEjb();
   }
   private void showGUI(){
      System.out.println("**********************");
      System.out.println("Welcome to Book Store");
      System.out.println("**********************");
      System.out.print("Options 
1. Add Book
2. Exit 
Enter Choice: ");
   }
   private void testStatelessEjb(){
      try {
         int choice = 1; 
         LibrarySessionBeanRemote libraryBean = 
         (LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
         while (choice != 2) {
            String bookName;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();                    
               libraryBean.addBook(bookName);          
            }else if (choice == 2) {
               break;
            }
         }
         List<String> booksList = libraryBean.getBooks();
         System.out.println("Book(s) entered so far: " + booksList.size());
         for (int i = 0; i < booksList.size(); ++i) {
         System.out.println((i+1)+". " + booksList.get(i));
         }
         LibrarySessionBeanRemote libraryBean1 = 
         (LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
         List<String> booksList1 = libraryBean1.getBooks();
         System.out.println(
         "***Using second lookup to get library stateless object***");
         System.out.println(
         "Book(s) entered so far: " + booksList1.size());
         for (int i = 0; i < booksList1.size(); ++i) {
            System.out.println((i+1)+". " + booksList1.get(i));
         }
      } catch (Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }finally {
         try {
            if(brConsoleReader !=null){
               brConsoleReader.close();
            }
         } catch (IOException ex) {
            System.out.println(ex.getMessage());
         }
      }
   }  
}


運行客戶端訪問EJB

在項目資源管理器中找到EJBTester.java。右鍵單擊EJBTester類并選擇運行文件 。


驗證Netbeans控制臺下面的輸出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. Learn Java
***Using second lookup to get library stateless object***
Book(s) entered so far: 0
BUILD SUCCESSFUL (total time: 13 seconds)

在下面的章節(jié)中,我們將討論這個完整的EJB應(yīng)用程序的多個方面。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號