10

How is the session defined in @SessionScoped CDI bean?
Is this annotation valid only when called from Servlet container, where the session is well defined in form of HttpSession?

If not, than how an EJB with @Inject @SessionScoped MyBean myBean can know what the session really is? I mean, methods of this EJB could have been invoked by a standalone client, RESTful WS or by some other view.
What should happen in such case? Should the annotation have no meaning, should it inject fresh MyBean instance for each request or maybe it should retain the same instance across all requests?

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82

1 Answers1

3

Taken from the @SessionScoped specification

The session scope is active:

during the service() method of any servlet in the web application, during the doFilter() method of any servlet filter and when the container calls any HttpSessionListener, AsyncListener or ServletRequestListener.

So in short, yes. It is bound to the HttpSession. Also:

The session context is shared between all servlet requests that occur in the same HTTP session. The session context is destroyed when the HTTPSession times out, after all HttpSessionListeners have been called, and at the very end of any request in which invalidate() was called, after all filters and ServletRequestListeners have been called.

  • Really, how else is a Session defined even for something like a SFSB? Of course there's nothing prohibiting you from creating your own scope and tying it to whatever you like. – LightGuard Nov 23 '11 at 05:57
  • @LightGuard, I guess that in SFSB the "session" lasts from SFSB instantiation to it's removal (or timeout). So as long as I have a reference to it, I'll hit the same environment (session). – Piotr Nowicki Nov 23 '11 at 13:39
  • @Gonzalo, thanks for this information. I wonder - what should happen if I'd use `@SessionScoped` bean in an environment where there is no such scope (i.e. REST WS as mentioned in question). Each request is treated as a new session? What about SFSB, as LightGuard mentioned. Will the `@SessionScoped` refer to the `HttpSession` session or the SFSB session? – Piotr Nowicki Nov 23 '11 at 13:42
  • My understanding is that @SessionScoped acts as the glue between the web layer and your EJBs. I doubt that the annotation would have any effect on a remote EJB called from a Swing client. Remember also that JSF session is backed by HttpSession too so it gets transferred to your EJBs as HttpSession. – Gonzalo Garcia Lasurtegui Nov 23 '11 at 16:27
  • Thanks, I'll try to check how the annotation will react upon REST invocation. – Piotr Nowicki Nov 26 '11 at 15:06
  • Just to update - in Glassfish 3.1.1 when `@SessionScoped` is used with REST - it treats every request as separate session, so every request has fresh instance created. Very reasonable. – Piotr Nowicki Nov 27 '11 at 23:56