How to implement the Add to cart option within a JSP page in a basic shopping cart application?
-
19-06-2021 - |
Question
I am working on an basic Shopping Cart
assignment in Springs
. The functionalities of the assignment are just to display a given set of products - with info (with an add to cart button). My problem is, integrating the Add button click
with the shopping cart display in the JSP
page.
How to use application session to obtain and persist information across multiple "Add
" button clicks?
Here is the code snippet:
<script type="text/javascript">
var noOfClicks = 0; // Used to count the number of Clicks.
function button_click() {
noOfClicks++; // On click of the button the value is incremented.
document.getElementById("item").value = noOfClicks;
}
</script>
How do I check if the button is clicked and add it to cart with its attributes (Quantity, Price etc) in a separate summary table?
Solution
You can use session scoped spring beans for shopping cart. It means that this bean is created when a new HttpSession is created and preserved as long as the HttpSession is valid. Spring uses AOP to extract the sessionId from the httprequest and manage the lifecycle of the bean.
In the action class of 'Add' activity, access the session object and add the selected item to the session cart object.