I finally arrived at a crossroad! The requirements for this project also include the use of Stateful Session Beans. Googoling around I discovered that Stateful Beans are often used for maintaining Shopping Carts, due to their ability to track the whole user session. I also found some tutorials on how implement them. Intuitively the implementation of a shopping cart can be made by using simply the HttpSession, however Stateful Beans have considerable advantages, as this link points out: http://www.java-tips.org/java-ee-tips/enterprise-java-beans/choosing-between-httpsession-and-stateful-session.html
So I created a Stateful bean called ShoppingCart implementing the Remote interface ShoppingCartInterface. However I was not sure on how reference it in the servlets. I tried using the annotation @EJB to inject the bean, but it didn't work. Finally, digging out some stackoverflow questions, I found what I was looking for: http://stackoverflow.com/questions/2811312/stateful-ejbs-in-web-application and http://stackoverflow.com/questions/2833457/how-do-i-obtain-a-new-stateful-session-bean-in-a-servlet-thread
I had to create an object ShoppingCart and save it in the HttpSession, in order to be used across requests. I decided to create an instance of ShoppingCart when the customer goes in the Management section of the application. So using these few lines of code:
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
try {
Context ctx = new InitialContext();
cart = (ShoppingCart) ctx.lookup("java:comp/env/cart");
session.setAttribute("cart", cart);
}
}
everything was magically working.
Nessun commento:
Posta un commento