users@glassfish.java.net

Re: Cannot lookup an EJB in JNDI from a servlet.

From: <glassfish_at_javadesktop.org>
Date: Tue, 22 May 2007 12:16:40 PDT

Many implementations provide some way to access EJBs through a direct global JNDI name.
However, doing so is NOT portable. In some cases there's a need to do a direct global JNDI
lookup for Remote EJBs, such as client code running in a non-Java EE web container like
Tomcat or Resin. However, whenever you have code running within a Java EE component it's
always best to use the portable approach, which is to declare a dependency on the EJB
(either through the deployment descriptor or annotation) and either inject or lookup that
dependency via the component naming environment.

If you're coding a J2EE 1.4 application, you need to use the deployment descriptor approach.
Pick a name for your EJB dependency and look it up in the code as follows :

(LocalTheSlsbHome)new InitialContext().lookup("java:comp/env/myejbref");

Then declare an ejb-local-ref in your web.xml. The ejb-ref-name is the same as the
portion of the lookup string after "java:comp/env", so in this case it would be
<ejb-ref-name>myejbref</ejb-ref-name>. "myejbref" is not a global JNDI name.
It's just a unique named location within the web component's private naming environment.

The ejb-link element of ejb-local-ref contains the ejb-name of the target EJB.
That comes from the ejb-name element of the target EJB's ejb-jar.xml.

There is no need to use any global JNDI names for local EJBs, so you don't even
need sun-ejb-jar.xml.

You can find more information on some of these topics in our EJB FAQ :

https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html
[Message sent by forum member 'ksak' (ksak)]

http://forums.java.net/jive/thread.jspa?messageID=218400