When using a Stateful EJB, how does the server know who the EJB is associated with if the client does not have an active session? I have used stateless EJB's before, but am now trying to learn how to use stateful EJB's. I was thinking of implementing my shopping cart as a stateful EJB, instead of having a POJO Cart that I add as an attribute in the user's session. But since a Stateful EJB isn't explicitly added as an attribute in the HttpSession, how does the server associate the client with the stateful EJB?
-
The server cannot associate the client with a session unless it has been added (or you're using `@Inject` and the stateful session bean is `@SessionScoped`). What gives you the impression that it is? – Brett Kail Sep 26 '14 at 03:31
-
I thought that with stateful EJB's, when I make a request to run a method in the stateleful EJB, the same bean is serving a single client, so I wasn't sure what the connection was between the bean and that 1 client. – user1154644 Sep 26 '14 at 20:16
-
The stateful session bean is created when the client performs the lookup. The proxy that is returned from the lookup contains some kind of reference/ID to the specific bean instance, so when the client makes subsequent calls on the proxy, it is connected back to the specific bean instance. – Brett Kail Sep 26 '14 at 23:05
1 Answers
The EJB doesn't technically need to have access to the JSESSION_ID of the client because, like any basic pojo, it's alive and usable, as long as the calling client is alive. Once the calling client is destroyed or otherwise relinquishes control of the SFSB, the bean is liable to be passivated or destroyed (and hence "forget" the conversation)
From the Oracle JavaEE-6 tutorial
The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state
Think of it the same way you get hold of a regular java object in a has-a relationship: once you've set the composed object to null, you've basically ended your conversation with that object. The same applies here (sort of). There's no need for the client to pass specific session information to the EJB. The EJB's normal lifecycle and annotations (specifically @Remove
) take care care of everything else.
A word of caution about SFSBs: They are heavyweight and they last longer than SLSBs. Don't use them unless you really need a full-scale EJB's trappings. In many cases, a plain HttpSession and an SLSB would suffice.
Further Reading

- 20,559
- 3
- 52
- 104
-
the caution is not necessarily true. There are patterns to work with SFSBs that lets you scale an app to avoid boiler plate code and anemic models provoked by SLSBs. Oracle doc says to not overuse a SLSBs unless you really have *many* users – Sergio Sep 27 '14 at 13:18