【问题标题】:How can I call an EJB3 session bean in a JSP?如何在 JSP 中调用 EJB3 会话 bean?
【发布时间】:2016-12-08 12:21:35
【问题描述】:

我正在使用 EJB 和 JPA 在 Eclipse 中开发一个应用程序。

我的会话 bean 是:

    package itso.bank.session;

import itso.bank.entities.Account;
import itso.bank.entities.Customer;
import itso.bank.entities.Transaction;
import itso.bank.exception.ITSOBankException;
import itso.bank.service.EJBBankService;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.*;

/**
 * Session Bean implementation class EJBBankBean
 */
@Stateless
public class EJBBankBean implements EJBBankService {

    @PersistenceContext (unitName="RAD8JPA", type=PersistenceContextType.TRANSACTION)
    private EntityManager entityMgr;
    /**
     * Default constructor. 
     */
    public EJBBankBean() {
        // TODO Auto-generated constructor stub
    }

    public void addCustomer(Customer customer) throws ITSOBankException {
        System.out.println("addCustomer: " + customer.getSsn());
        entityMgr.persist(customer);
    }

    public void closeAccount(String ssn, String id) throws ITSOBankException {
        System.out.println("closeAccount: " + id + " of customer " + ssn);

        Account account = getAccount(id);
        Transaction[] trans = getTransactions(id);
        for (Transaction tx : trans) {
            entityMgr.remove(tx);
        }
        entityMgr.remove(account);
        System.out.println("closed account with " + trans.length + " transactions");
    }

    public void deleteCustomer(String ssn) throws ITSOBankException {
        System.out.println("deleteCustomer: " + ssn);
        Customer customer = getCustomer(ssn);
        Account[] accounts = getAccounts(ssn);
        for (Account acct : accounts) {
            closeAccount(ssn, acct.getId());
        }
        entityMgr.remove(customer);
    }

    public void deposit(String id, BigDecimal amount) throws ITSOBankException {
        System.out.println("deposit: " + id + " amount " + amount);
        Account account = getAccount(id);
        try {
            Transaction tx = account.processTransaction(amount, Transaction.CREDIT);
            entityMgr.persist(tx);
        } catch (Exception e) {
            throw new ITSOBankException(e.getMessage());    
        }
    }

    public Account getAccount(String id) throws ITSOBankException {
        System.out.println("getAccount: " + id);
        try {
            return entityMgr.find(Account.class, id);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            throw new ITSOBankException(id);
        }
    }

    public Account[] getAccounts(String ssn) throws ITSOBankException {
        System.out.println("getAccounts: " + ssn);
        Query query = null;
        try {
            query = entityMgr.createNamedQuery("getAccountsBySSN"); 
            query.setParameter(1, ssn);
            List<Account> accountList = query.getResultList();
            Account[] array = new Account[accountList.size()];
            return accountList.toArray(array);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            throw new ITSOBankException(ssn);
        }
    }

    public Customer getCustomer(String ssn) throws ITSOBankException {
        System.out.println("getCustomer: " + ssn);
        //Query query = null;
        try {
            //query = entityMgr.createNamedQuery("getCustomerBySSN");   
            //query.setParameter(1, ssn);
            //return (Customer)query.getSingleResult();
            return entityMgr.find(Customer.class, ssn);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            throw new ITSOBankException(ssn);
        }
    }

    public Customer[] getCustomers(String partialName) throws ITSOBankException {
        System.out.println("getCustomer: " + partialName);
        Query query = null;
        try {
            query = entityMgr.createNamedQuery("getCustomersByPartialName");
            query.setParameter(1, partialName);
            List<Customer> beanlist = query.getResultList();
            Customer[] array = new Customer[beanlist.size()];
            return beanlist.toArray(array);
        } catch (Exception e) {
            throw new ITSOBankException(partialName);
        } 
    }

    public Customer[] getCustomersAll() {
        System.out.println("getCustomers: all");
        Query query = null;
        try {
            query = entityMgr.createNamedQuery("getCustomers"); 
            List<Customer> beanlist = query.getResultList();
            Customer[] array = new Customer[beanlist.size()];
            return beanlist.toArray(array);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            return null;
        }
    }

    public Transaction[] getTransactions(String accountID) throws ITSOBankException {
        System.out.println("getTransactions: " + accountID);
        Query query = null;
        try {
            query = entityMgr.createNamedQuery("getTransactionsByID");  
            query.setParameter(1, accountID);
            List<Transaction> transactionsList = query.getResultList();
            Transaction[] array = new Transaction[transactionsList.size()];
            return transactionsList.toArray(array);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            e.printStackTrace();
            throw new ITSOBankException(accountID);
        }
    }

    public String openAccount(String ssn) throws ITSOBankException {
        System.out.println("openAccount: " + ssn);
        Customer customer = getCustomer(ssn);
        int acctNumber = (new java.util.Random()).nextInt(899999) + 100000;
        String id = "00" + ssn.substring(0, 1) + "-" + acctNumber;
        Account account = new Account();
        account.setId(id);
        entityMgr.persist(account);

        List<Customer> custSet = Arrays.asList(customer);
        account.setCustomers(custSet);
        System.out.println("openAccount: " + id);
        return id;
    }

    public void transfer(String idDebit, String idCredit, BigDecimal amount) throws ITSOBankException {
        System.out.println("transfer: " + idCredit + " " + idDebit + " amount " + amount);
        withdraw(idDebit, amount);
        deposit(idCredit, amount);
    }

    public void updateCustomer(String ssn, String title, String firstName, String lastName) throws ITSOBankException {
        System.out.println("updateCustomer: " + ssn);
        Customer customer = getCustomer(ssn);
        customer.setTitle(title);
        customer.setLastName(lastName);
        customer.setFirstName(firstName);
        System.out.println("updateCustomer: " + customer.getTitle() + " " + customer.getFirstName() + " " + customer.getLastName());
    }

    public void withdraw(String id, BigDecimal amount) throws ITSOBankException {
        System.out.println("withdraw: " + id + " amount " + amount);
        Account account = getAccount(id);
        try {
            Transaction tx = account.processTransaction(amount, Transaction.DEBIT);
            entityMgr.persist(tx);
        } catch (Exception e) {
            throw new ITSOBankException(e.getMessage());    
        }
    }


}

我的 JPA 已经连接到 EJB 项目。我的问题是如何在不需要 servlet 的情况下从 Java 服务器页面调用会话 bean?

谢谢!

【问题讨论】:

    标签: java jsp ejb javabeans


    【解决方案1】:

    简单地说,通过@Named注解来注解服务实现类

    @Stateless
    @Named("eJBBankBean")
    public class EJBBankBean implements EJBBankService {....}
    

    在您的 JSP 文件中,使用: #{ejbBankBean.yourServiceMethod(parameter1_ifAny,parameter2_ifAny)}

    @Named 是 CDI 注释,没有 @Named EJB Bean 在 JSP EL 即“$”或统一 EL 即“#”中不可见

    【讨论】:

    • 这是最好的办法
    • 这看起来很有希望,但我无法让它发挥作用。似乎缺少一些步骤。例如:如何将 EJBBankBean 注入 JSP?你不应该使用本地接口,就像在带有@EJB 注释的servlet 中一样吗? (顺便说一句,“eJBBankBean”是错字吗?)
    【解决方案2】:

    我想一定有不使用 MVC 框架的原因。

    所以,假设您使用的是本地接口,这是我记得的从 .jsp 调用 ejb 的最简洁和标准的方式

    <ejb-local-ref>
        <ejb-ref-name>MyBeanName</ejb-ref-name>
        <ejb-ref-type>Session</ejb-ref-type>
        <local>com.myapp.ejb.MyBeanLocal</local>
    </ejb-local-ref>
    

    然后从你的jsp

    <%
    String lookupUrl = "java:comp/env/MyBeanName";
    Context ctx = new javax.naming.InitialContext();
    MyBeanNameLocal ejbLocal = (MyBeanNameLocal) ctx.lookup(lookupUrl);
    
    String output = ejbLocal.myBusinessMethod();
    %>
    

    【讨论】:

    • 这是过时的方法。 EJB Better 适用于 Java EE 中的 CDI 和您的解决方案,我认为是基于 9 年的 J2EE 黑色日子。如果我错了,请纠正我。
    • 嗯,9 年前的方法是从 JSP 调用 EJB。话虽如此,您是对的,但是某些应用程序服务器在将 EJB 注入 JSP 时存在问题/错误。 Glassfish 是/曾经是一个例子,我很久没有关注应用服务器了。这就是我发布旧标准方法的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多