欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

② EJB有状态的bean

程序员文章站 2022-03-11 08:59:52
...

② EJB有状态的bean

1.定义

有状态会话bean是一种企业bean的它与客户保持会话状态。有状态会话Bean根据其名声在它的实例变量相关的客户端状态。 EJB容器创建一个单独的有状态会话bean来处理客户端的每个请求。只要请求范围已经结束,statelful会话bean被销毁。类似于spring中的多例或者session会话域。

2.注意事项

2.1 服务端注意事项(EJBServerStateFul)

需要加上@Stateful注解,表示该类为有状态的bean

@Stateful
@Remote
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote {

2.2 客户端注意事项(EJBClientStateFul)

我们在进行远程调用的时候,一定要加上我们的状态,否则会报错,找不到状态,因为是有状态的bean在提供服务,所以我们的状态就显得格外的重要了。(具体如何加状态,见文章1)

libraryStatefulSessionBeanRemote = (LibraryStatefulSessionBeanRemote) context.lookup("ejb:/EJBServerStateFul_war_exploded/LibraryStatefulSessionBean!pers.jhl.session.stateless.LibraryStatefulSessionBeanRemote?stateful=TMingYi");

3.完整代码

(基础的集合存书)

3.1 服务端

LibraryStatefulSessionBeanRemote:
public interface LibraryStatefulSessionBeanRemote  {
    void addBook(String bookName);
    List getBooks();
}
LibraryStatefulSessionBean:
//表示有状态的EJB,每一个请求打过来,都会产生一个新的对象
@Stateful
@Remote
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;
    }
}

3.2 客户端

LibraryStatefulSessionBeanRemote:
public interface LibraryStatefulSessionBeanRemote  {
    void addBook(String bookName);
    List getBooks();
}

EJBTester(主方法):

import java.awt.print.Book;
import java.io.*;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBTester {

    static LibraryStatefulSessionBeanRemote libraryStatefulSessionBeanRemote;

    static {
        try{
            Properties pro = new Properties();
            pro.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
            pro.put("jboss.naming.client.ejb.context",true);

            Context context = new InitialContext(pro);
            libraryStatefulSessionBeanRemote = (LibraryStatefulSessionBeanRemote) context.lookup("ejb:/EJBServerStateFul_war_exploded/LibraryStatefulSessionBean!pers.jhl.session.stateless.LibraryStatefulSessionBeanRemote?stateful=TMingYi");
        }catch(NamingException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<String> books = libraryStatefulSessionBeanRemote.getBooks();
        for (String book : books) {
            System.out.println(book);
        }
    }
    }