EJB - 有狀態Bean



有狀態會話Bean是一種企業Bean,它保留與客戶端的會話狀態。顧名思義,有狀態會話Bean在其例項變數中保留關聯的客戶端狀態。EJB容器會建立一個單獨的有狀態會話Bean來處理客戶端的每個請求。一旦請求範圍結束,有狀態會話Bean就會被銷燬。

建立有狀態EJB的步驟

以下是建立有狀態EJB所需的步驟:

  • 建立一個公開業務方法的遠端/本地介面。

  • 此介面將由EJB客戶端應用程式使用。

  • 如果EJB客戶端與需要部署EJB會話Bean的環境相同,則使用@Local註解。

  • 如果EJB客戶端與需要部署EJB會話Bean的環境不同,則使用@Remote註解。

  • 建立一個實現上述介面的有狀態會話Bean。

  • 使用@Stateful註解表示它是有狀態Bean。EJB容器會在部署過程中讀取此註解,自動建立相關的配置或介面。

遠端介面

import javax.ejb.Remote;
 
@Remote
public interface LibraryStatefulSessionBeanRemote {
   //add business method declarations
}

有狀態EJB

@Stateful
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote {
   //implement business method 
}

示例應用程式

讓我們建立一個測試EJB應用程式來測試有狀態EJB。

步驟 描述
1

EJB - 建立應用程式章節所述,建立一個名為EjbComponent的專案,放在com.tutorialspoint.stateful包下。您也可以使用EJB - 建立應用程式章節中建立的專案,以便理解本節的有狀態EJB概念。

2

EJB - 建立應用程式章節所述,建立LibraryStatefulSessionBean.javaLibraryStatefulSessionBeanRemote。保持其餘檔案不變。

3

清理並構建應用程式,以確保業務邏輯按要求工作。

4

最後,將應用程式以jar檔案的形式部署到JBoss應用伺服器。如果JBoss應用伺服器尚未啟動,它將自動啟動。

5

現在建立EJB客戶端,一個基於控制檯的應用程式,方法與EJB - 建立應用程式章節中建立訪問EJB的客戶端主題下所述相同。

EJBComponent(EJB模組)

LibraryStatefulSessionBeanRemote.java

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

LibraryStatefulSessionBean.java

package com.tutorialspoint.stateful;
 
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
 
@Stateful
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote {
    
   List<String> bookShelf;    
 
   public LibraryStatefulSessionBean() {
      bookShelf = new ArrayList<String>();
   }
 
   public void addBook(String bookName) {
      bookShelf.add(bookName);
   }    
 
   public List<String> getBooks() {
      return bookShelf;
   }
}
  • 一旦您將EjbComponent專案部署到JBOSS,請注意jboss日誌。

  • JBoss已自動為我們的會話Bean建立了一個JNDI條目 - LibraryStatefulSessionBean/remote

  • 我們將使用此查詢字串來獲取型別為com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote的遠端業務物件。

JBoss應用伺服器日誌輸出

...
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibraryStatefulSessionBean/remote - EJB3.x Default Remote Business Interface
   LibraryStatefulSessionBean/remote-com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryStatefulSessionBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote ejbName: LibraryStatefulSessionBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
 
   LibraryStatefulSessionBean/remote - EJB3.x Default Remote Business Interface
   LibraryStatefulSessionBean/remote-com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote - EJB3.x Remote Business Interface
...   

EJBTester(EJB客戶端)

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
  • 這些屬性用於初始化java命名服務的InitialContext物件。

  • InitialContext物件將用於查詢有狀態會話Bean。

EJBTester.java

package com.tutorialspoint.test;
   
import com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote;
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 \n1. Add Book\n2. Exit \nEnter Choice: ");
   }
   
   private void testStatelessEjb() {
 
      try {
         int choice = 1; 
 
         LibraryStatefulSessionBeanRemote libraryBean =
         LibraryStatefulSessionBeanRemote)ctx.lookup("LibraryStatefulSessionBean/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();
               Book book = new Book();
               book.setName(bookName);
               libraryBean.addBook(book);          
            } else if (choice == 2) {
               break;
            }
         }
 
         List<Book> booksList = libraryBean.getBooks();
 
         System.out.println("Book(s) entered so far: " + booksList.size());
         int i = 0;
         for (Book book:booksList) {
            System.out.println((i+1)+". " + book.getName());
            i++;
         }       
         LibraryStatefulSessionBeanRemote libraryBean1 = 
            (LibraryStatefulSessionBeanRemote)ctx.lookup("LibraryStatefulSessionBean/remote");
         List<String> booksList1 = libraryBean1.getBooks();
         System.out.println(
            "***Using second lookup to get library stateful 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());
         }
      }
   }
}

EJBTester執行以下任務:

  • 從jndi.properties載入屬性並初始化InitialContext物件。

  • 在testStatefulEjb()方法中,使用名稱“LibraryStatefulSessionBean/remote”進行jndi查詢,以獲取遠端業務物件(有狀態ejb)。

  • 然後向用戶顯示一個圖書館商店使用者介面,並要求他/她輸入選擇。

  • 如果使用者輸入1,系統會要求輸入書名並使用有狀態會話Bean的addBook()方法儲存書籍。會話Bean將其儲存在其例項變數中。

  • 如果使用者輸入2,系統將使用有狀態會話Bean的getBooks()方法檢索書籍並退出。

  • 然後再次使用名稱“LibraryStatefulSessionBean/remote”進行jndi查詢,以獲取遠端業務物件(有狀態EJB),並列出書籍。

執行客戶端以訪問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 stateful object***
Book(s) entered so far: 0
BUILD SUCCESSFUL (total time: 13 seconds)

再次執行客戶端以訪問EJB

在專案資源管理器中找到EJBTester.java。右鍵單擊EJBTester類並選擇執行檔案

在Netbeans控制檯中驗證以下輸出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 0
***Using second lookup to get library stateful object***
Book(s) entered so far: 0
BUILD SUCCESSFUL (total time: 12 seconds)
  • 上面顯示的輸出表明,對於每次查詢,都會返回不同的有狀態EJB例項。

  • 有狀態EJB物件僅保留單個會話的值。在第二次執行中,我們沒有獲得任何書籍的值。

廣告
© . All rights reserved.