📜  EJB-有状态Bean

📅  最后修改于: 2020-11-16 06:13:59             🧑  作者: Mango


有状态会话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。

Step Description
1

Create a project with a name EjbComponent under a package com.tutorialspoint.stateful as explained in the EJB − Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand stateful EJB concepts.

2

Create LibraryStatefulSessionBean.java and LibraryStatefulSessionBeanRemote as explained in the EJB − Create Application chapter. Keep rest of the files unchanged.

3

Clean and Build the application to make sure business logic is working as per the requirements.

4

Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.

5

Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access 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 bookShelf;    
 
   public LibraryStatefulSessionBean() {
      bookShelf = new ArrayList();
   }
 
   public void addBook(String bookName) {
      bookShelf.add(bookName);
   }    
 
   public List getBooks() {
      return bookShelf;
   }
}
  • 在JBOSS上部署EjbComponent项目后,请注意jboss日志。

  • JBoss已经为我们的会话bean − LibraryStatefulSessionBean / remote自动创建了一个JNDI条目。

  • 我们将使用此查找字符串来获取类型为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 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 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 /远程”完成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对象仅保留单个会话的价值。与第二轮一样,我们没有得到任何书本的价值。