Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to lookup an EJB in Servlets?

 
Mellon Sun
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jimmy Clark
Ranch Hand
Posts: 2187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic