users@glassfish.java.net

Re: Stateful EJB3 and InitialContext query

From: <glassfish_at_javadesktop.org>
Date: Tue, 10 Jun 2008 07:55:16 PDT

> If two or more seperate servlets (or any class for
> that matter) have the same EJB injected, will the
> instance of the EJBs be different?

Yes. Injection of stateful session beans into servlet classes is not recommended for that
reason. The servlet threading model uses the same servlet class instance to process
all concurrent invocations. That conflicts with the stateful session bean single client
semantics.

>
> A HttpSession and ServletContext are scoped to the
> servlet.

Not true. The HttpSession is state associated with a particular client. It's available to
any web component called within the web invocation from that client.

ServletContext attributes are scoped to the web application as a whole.

>How do I share EJBs between a client session
> regardless of Servlet?

Put this at the top of your servlet :

@EJB(name="myejbref", beanInterface=<BeanInterface>.class)
public class MyServlet ...

Then, within the code lookup the reference as follows :

BeanInterface ref = (BeanInterface) new InitialContext().lookup("java:comp/env/myejbref");

Each call to lookup creates a reference to a new Stateful Session Bean instance.
Now you can store that reference in the HttpSession or a ServletContext attribute.
[Message sent by forum member 'ksak' (ksak)]

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