File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes How to lookup an EJB in Servlets? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "How to lookup an EJB in Servlets?" Watch "How to lookup an EJB in Servlets?" New topic

How to lookup an EJB in Servlets?

Mellon Sun
Ranch Hand

Joined: Feb 20, 2003
Posts: 126
After I defined this in the war's web.xml:
then I can lookup this ejb in a servlet via:

InitialContext ctx = new InitialContext();
StatefulSBLocal cart = (StatefulSBLocal) ctx.lookup("java:comp/env/ejb/cart");

Should I define the ejb ref in web.xml to lookup an EJB?
Can I access an EJB in Servlet without defining an ref in web.xml or annotating it by @EJB?

I tried to lookup my StatefulSBBean with JNDI names as "java:comp/env/ejb/StatefulSBBean", "ejb/StatefulSBBean" ...
Failed every time.
[ December 21, 2008: Message edited by: Mellon Sun ]

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Should I define the ejb ref in web.xml to lookup an EJB?

Not really, this conflicts with the three-tier programming style and model of J2EE. A better way to connect the web GUI (Presentation tier) to a EJB business component (Business tier) is to use a Business Delegate object.

Check out the design pattern documentation for Business Delegate at and pay close attention to the Problem section which covers why you shouldn't define the EJB reference in WEB.XML.

Jim Janssens
Ranch Hand

Joined: Sep 24, 2004
Posts: 210
I'm sorry, but there is nowhere a line that says that you must not define an EJB reference in the web.xml ?

According to me this has nothing to do with patterns either. Regardless how you communicatie with the EJB, using a business delegate, looking it up via a service locator etc, its ALWAYS good practise to define references tho those resources (in this case an EJB) in the web.xml...

However, you could also skip that, and use the global JNDI name of the resource, but you'll loose an extra layer of indirection. Supose the global name changes once on the production env, you have to adapt your code. Using a resource ref the deployer could simply alter the descriptor. And there are other advantages as well.

Secondly; if you are looking up an EJB from a servlet and you are on a J2EE 5 container, you might want to use DI with annotations. Just put an @EJB on the instance field.
I agree. Here's the link:
subject: How to lookup an EJB in Servlets?
It's not a secret anymore!