Many of you have asked or are stuck with the problem of how to maintain the shopping cart without login.
While it seems to be a little tricky, actually its fairly simple and has got more to do with the concept than the actual code that you might have to write for implementing this feature.
Coming to the concept. When a person wants to buy a Book, he/she will associate a quantity with it (at least 1). This Book-Quantity pair is an Item.
And a person would like to order more than 1 kind/type of Book. So a shopping Cart will comprise of many such Items.
So here we introduce 2 more Nouns and therefore 2 more models Item and Cart.
So a Cart will have an ArrayList of Items and Total Amount. An Item will have a Book and corresponding quantity. It will be good to have functions which can create an Item using Book Id, calculating sub-total for an Item and calculate Total for the Cart.
The logic for maintaining this Cart is as follows:
When the user tries to Add a Book to Cart (BuyBook or AddToCart link). In the corresponding Action pass the Book_Id. In the action do the following:
1. Get the Action Context.
2. Get the Action's session from the Context.
3. There are two functions called session's get() and session's put() . Using these two functions correctly, you will be able to implement the functionality.
4. For the first time, create a new Cart.
5. Create a new Item using the Book_Id.
6. Add this Item to the Cart Object.
7. Put this Cart object in the session using put().
8. When the user tries to buy another Book, fetch the Cart from session using get().
9. Create new Item and add to Cart.
10. Again put the cart back in session.
Keep on repeating Steps 8-9 will implement the required functionality. There is a little trick which you can use to detect whether the user is buying a book for first time which you need to figure out.
I hope this will help most of you. Comments and questions are most welcome.
Go through this link for more details on ActionContext
http://www.opensymphony.com/webwork/api/com/opensymphony/xwork/ActionContext.html
Thanks.
Thursday, November 22, 2012
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment