aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
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
Author

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:
<ejb-local-ref>
<ejb-ref-name>ejb/cart</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.mellon.StatefulSBLocal</local>
</ejb-local-ref>
then I can lookup this ejb in a servlet via:

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

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 ]

SCJP,SCWCD1.3,SCWCD1.4,SCJD,SCBCD5,SCEA5
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.

BusinessDelegate.html
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: http://aspose.com/file-tools
 
subject: How to lookup an EJB in Servlets?