This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori 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().