In the previous article, the mode1 model was used to realize product browsing. Based on the previous article, this article uses the mvc architecture to realize product purchase.
Running results:
Compared with the previous article, we have more shopping carts. Since when we purchase items, the shopping cart needs attributes to the purchased items and quantity, we use the map key value to save the purchased items.
Of course there is also a total price. The method of shopping cart is to add products and delete products to calculate the total price . The total price should be recalculated every time the product is added and deleted. The shopping cart product collection can only be instantiated once when the shopping cart is initialized.
package entity; import java.util.HashMap; public class Cart { //Shopping cart product collection private HashMap<Items,Integer> cart; //Total amount private double totalPrices; public Cart() { cart=new HashMap<Items, Integer>(); totalPrices=0.0; } public HashMap<Items, Integer> getCart() { return cart; } public void setCart(HashMap<Items, Integer> cart) { this.cart = cart; } public double getTotalPrices() { return totalPrices; } public void setTotalPrices(double totalPrices) { this.totalPrices = totalPrices; } //Add items into the shopping cart public boolean addToCart(Items item,int counts){ //If the current item has been added only increases the quantity if(cart.containsKey(item)){ cart.put(item, cart.get(item)+counts); }else{ cart.put(item, counts); } //Recalculate the price calTotalPrice(item.getPrice()*counts); return true; } //Remove items from the shopping cart public boolean removeFromCart(Items item){ if(cart!=null&&cart.containsKey(item)){ calTotalPrice(-item.getPrice()*cart.get(item)); cart.remove(item); } return true; } //Calculate the total amount private void calTotalPrice(double price){ totalPrices+=price; } } The doGett method of CartServlet performs corresponding processing according to the action
if (request.getParameter("action") != null) { action = request.getParameter("action"); if ("add".equals(action)) { // Add product if (addGoodsToCart(request, response)) { request.getRequestDispatcher("../success.jsp").forward( request, response); } else { request.getRequestDispatcher("../failure.jsp").forward( request, response); } } else if ("show".equals(action)) {// Show shopping cart request.getRequestDispatcher("../cart.jsp").forward(request, response); } else if ("delete".equals(action)) {// Delete item deleteGoodFromCart(request, response); request.getRequestDispatcher("../cart.jsp").forward(request, response); } } When we click on the product interface to put the cart, the number of the current product is transferred to the servlet class CartServlet of the cart. It starts processing the current item and putting the current item into the cart
Before putting it in the shopping cart, first determine whether it is the first time to create a shopping cart (there is definitely only one shopping cart, but not multiple). If it is the first time to create a shopping cart
Put the current shopping cart into session, and then call the getItemById(id) method through the ItemsDao object to obtain the product object. Then put the corresponding product object and product quantity into the shopping cart
//Add products to the shopping cart private boolean addGoodsToCart(HttpServletRequest request, HttpServletResponse response) { String id=request.getParameter("id"); String counts=request.getParameter("num"); Items item=dao.getItemById(Integer.parseInt(id)); //Discern whether it is the first time to create a shopping cart if(request.getSession().getAttribute("cart")==null){ Cart cart=new Cart(); request.getSession().setAttribute("cart", cart); request.getSession().setAttribute("dao", dao); } Cart cart=(Cart) request.getSession().getAttribute("cart"); //Add the item to the cart if(cart.addToCart(item, Integer.parseInt(counts))){ return true; }else{ return false; } } If you click View CartCartServlet Redirect to Cart page
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ page import="entity.Cart" %> <%@ page import="entity.Items" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cart.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link type="text/css" rel="stylesheet" href="css/style1.css" /> <script language="javascript"> function delcfm() { if (!confirm("Confirm to delete?")) { window.event.returnValue = false; } } </script> </head> <body> <h1>My shopping cart</h1> <a href="goods.jsp">Home</a> >> <a href="goods.jsp">Product List</a> <hr> <div id="shopping"> <form action="" method=""> <table> <tr> <th>Product name</th> <th>Product unit price</th> <th>Product price</th> <th>Purchase quantity</th> <th>Action</th> </tr> <% //First judge whether there is a shopping cart object in the session if(request.getSession().getAttribute("cart")!=null) { %> <!-- The start of the loop--> <% Cart cart = (Cart)request.getSession().getAttribute("cart"); HashMap<Items,Integer> goods = cart.getCart(); Set<Items> items = goods.keySet(); Iterator<Items> it = items.iterator(); while(it.hasNext()) { Items i = it.next(); %> <tr name="products" id="product_id_1"> <td><img src="images/<%=i.getPicture()%>" /><a href=""><%=i.getName()%></a></td> <td><%=i.getPrice() %></td> <td id="price_id_1"> <span><%=i.getPrice()*goods.get(i) %></span> <input type="hidden" value="" /> </td> <td> <%=goods.get(i)%> </td> <td> <a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">Delete</a> </td> </td> </tr> <% } %> <!--end of loop--> </table> <div><span id="total">Total: <%=cart.getTotalPrices() %>¥</span></div> <% } %> <div><input type="submit" value="" /></div> </form> </div> </body> </html> When clicking on Delete Product CartServlet class calls the method to delete the product
// Delete items from shopping cart private boolean deleteGoodFromCart(HttpServletRequest request, HttpServletResponse response) { // Get the shopping cart object from session Cart cart = (Cart) request.getSession().getAttribute("cart"); if (cart != null) { int id = Integer.parseInt(request.getParameter("id")); if (cart.removeFromCart(dao.getItemById(id))) { return true; } } return false; }The logic code is mainly as above.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.