EJB 注入 - JNDI 查找失败

EJB injection - JNDI lookup fails

所以我开始使用 Netbeans 8.2 开发 Java EE 企业应用程序。这是关于一家商店,你有一个购物车,你必须正确地存储每个客户的会话。

在 NetBeans 中我有:Shop-ejbShop-war

Shop-ejb 包含以下 类:

然后,Shop-war 包含以下 servlet:

我正在使用 GlasshFish,当我访问 http://localhost:8080/Shop-war/Servlet 时,我在 NetBeans 控制台上收到以下错误:

Grave:   javax.naming.NamingException: Lookup failed for 'java:global/Shop/Shop-ejb/CartBean!cart.CartLocal' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: Shop]

我知道 lookup 失败了,但我尝试了多种方法,但没有结果。希望你能帮助我。

您需要在 web.xml 上设置一个 <ejb-local-ref> 标签:

例如:

<ejb-local-ref>
        <ejb-ref-name>CartLocal</ejb-ref-name>
        <ejb-ref-type>Session</ejb-ref-type>
        <local>cat.CartLocal</local>
        <ejb-link>CartLocal</ejb-link>
</ejb-local-ref>

并通过查找访问:

try {
        if (carrito == null) {
            InitialContext ic = new InitialContext();
            carrito = (CartLocal) ic.lookup("java:comp/env/CartLocal");

            request.getSession().setAttribute(CARRITO_SESSION_KEY, carrito);
        }
    } catch (NamingException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }