Question

I deployed a web application on the localhost GlassFish server. This application takes order information from user and stores it in a List type variable in a Stateless Session Bean.The list object is created in the constructor.

I open the order page and add multiple orders in it. When I open the show orders page in different tabs and different browsers, it displays all the order information bean correctly, as though the state is maintained in a Stateless Bean!

I think this behavior is wrong as each browser/tab should create different session with the server and new order information should be shown for each browser/tab. How can this behavior be explained?

Was it helpful?

Solution

Your use case is precisely what a stateful session bean is for, if you want your List object to be maintained across method invocations, and if you want each session to be assigned its own bean.

Stateless session beans are pooled and made available to any session. But your instance fields are not guaranteed to be cleared, so you can't depend on them being cleared. The behavior that you are seeing is not unexpected. Even if you were successful in creating separate sessions in multiple tabs, those sessions could very well have been (and apparently were) assigned the same session bean. That's because the associated method invocations occurred at different points in time. Now if the associated method invocations occurred simultaneously instead, then the platform would have assigned a different stateless bean to each invocation (session). In that case, you'd see different behavior.

See also;

conversational state of session beans

and

Stateless and Stateful Enterprise Java Beans


Never let what you can't do get in the way of what you can do.

OTHER TIPS

Problem: Stateful Session Bean was not maintaining separate state per client. In the example I tried, I input orders from the JSP page, which were stored in a List in a Stateful Session Bean. When I called the same URL from a different browser (i.e. a different session), the list of orders input in the previous session were visible. The same EJB was getting referenced in both sessions. (Verified by sysouts)

It's like saying, the shopping cart of some other user was directly visible to me as if they were my orders!!

Solution: Used an HttpSessionListener and got the dependency of the Stateful EJB through JNDI, in sessionCreated(HttpSessionEvent se) method. Next, added the stateful EJB in an HttpSession and accessed the EJB through session in servlet.

Suggestions for using JNDI, instead of DI, for Stateful Session Bean and Adding EJB to HttpSession are given in the answer above. Don't know if it is the proper way to go, but it works!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top