This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am learning how sessions work in the browser by using a very simple shopping cart application. I have a button that calls the following servlet which then adds an item (a simple string from a textfield on the webpage) to the shopping cart:
I then forward to a page that tells me what item I have just added. I then click the back button on the browser and can add another item.
My problem is that I have another button (on the same page where I can add items) to display all the items in the cart. This button takes me to another page but it only displays the last item I entered. Say I enter crisps, chocolate and fudge, fudge will only show up. Here is the code for that servlet:
Since I can read the last item I don't know if I am re-instantiating the shopping cart every time I call the servlet that adds the item. The shopping carts 'addItem' method simply adds a 'shoppingCartItem' (which has a String variable called name) to an ArrayList of items in the shopping cart. What am I doing wrong here?
Swetha Popuri wrote:Hey, personally I dont use the back button of the browser while doing this kind of stuff.
Yes, but users will likely do so and the web app met be tolerant of this and continue to work correctly.
Hi Bear, I would always use the back button by instinct so how do I get around the problem of reinstantiating the shopping cart? If each user is to have their own cart I can't put it in the application scope. Am I at least on the right track here? Thanks.
Bear Bibeault wrote:P.S. Have you read this article? It outlines proper application flow.
No, but I will thanks. So where should I instantiate the cart if not in the session? Would it be possible to check if the cart exists in the session first and if not then create it ie. create only on the first request?
Joined: Jul 19, 2012
One way is if it is the first request, the attribute 'cart' is null in the session.
First thing is init() method is called only once in Servlet's lifecycle and that too before the servlet is ready to serve user's request.
This method is called by the Container say for eg. tomcat .
Then when a request for this servlet comes in....container either creates a new thread for this servlet or picks one from thread pool if available...and calls it doServiceMethod() which in turn calls doGet() or doPost()
depending on the type of request.
So if you want to check the names of threads serving your request try printing those in either doGet() or doPost().
Hope this helps.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com