I have a stateful EJB acting as a shopping cart. I have two servlets, one of them is used for adding products to the shopping cart. The other is used to retrieve the shopping cart information, ie. the products and quantities of products in the cart.
The shopping cart holds its state between requests as it should for the AddToCartServlet. Yet when using the ShoppingCartInfoServlet the list of products in the shopping cart is 0 even though there are multiple products in the cart. So it seems I am not getting the same EJB when I am in the ShoppingCartInfoServlet. Surely it should be the same EJB as I have annotated it as @Stateful?
@Stateful
public class ShoppingCart {
List<Product> products;
...
}
public class AddToCartServlet extends HttpServlet {
@EJB
ShoppingCart shoppingCart;
...
}
public class ShoppingCartInfoServlet extends HttpServlet {
@EJB
ShoppingCart shoppingCart;
...
}
Stateful means the same client (the servlet in this case) will keep talking to the same instance over multiple method invocations.
Another client (Servlet) will get it’s own instance. You would have to store the bean in the http session to achieve what you want.
Using a Stateful Session Bean to track an user's session