The MVC architecture realizes the purchase of goods (II.) _java

Source: Internet
Author: User

In the previous article, the MODE1 model was used to realize the product browsing, and this article, based on the previous article, uses the MVC architecture to achieve the purchase of the goods.
Run Result:

Compared with the previous article we have more shopping cart class
As we purchase items, the shopping cart will need the same attributes as the purchased goods and quantity, so we use the key value of map to save the purchased goods.
Of course there is a total price, the method of shopping cart has added goods delete goods calculate Total price The total price should be recalculated every time the item is added and the item is deleted the shopping cart collection is instantiated only once when the cart is initialized

Package entity; 
 
Import Java.util.HashMap; 
  public class Cart {//Shopping cart Merchandise 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; 
  The public void Settotalprices (double totalprices) {this.totalprices = totalprices; }//Add items into Cart public boolean addToCart (items item,int counts) {//If the current item has been added only add quantity if (Cart.containskey ite 
    m)) {Cart.put (item, Cart.get (item) +counts); 
    }else{cart.put (item, counts); 
    //Recalculate Price Caltotalprice (Item.getprice () *counts); 
  return true; //Remove items from Shopping cart public boolean removefromcart (items) {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;  } 
}

Cartservlet's Dogett method is processed 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)) {//Display cart 
        Request.getrequestdispatcher (".. /cart.jsp "). Forward (request, 
            response); 
      } else if (" delete ". Equals (Action)) {//delete items 
        Deletegoodfromcart (request, response); 
        Request.getrequestdispatcher (".. /cart.jsp "). Forward (request, 
            response); 
      } 
     

When we click on the product interface to put the number of the current item into the shopping cart, the servlet class Cartservlet starts processing the current item and puts the current item into the shopping cart.

Before you put it in the shopping cart, first determine if it is the first time you create a shopping cart (the cart must have only one number) if it is the first time you create a cart cart
Put the current cart in session, and then use the Itemsdao object to invoke the GetItemByID (ID) method to get the commodity object. Then put the corresponding merchandise objects and quantity of goods into the shopping cart

Add merchandise to 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)); 
    Determine if this is the first time a shopping cart is created 
    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 Item to Cart 
    if (Cart.addtocart (item, Integer.parseint (counts))) {return 
      true; 
    } else{return 
      false; 
    } 
   

If you click on the view shopping cart Cartservlet Redirect to the shopping 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" >  

When clicked on Delete merchandise Cartservlet class Call Delete product method

Remove merchandise from Shopping cart 
  private Boolean deletegoodfromcart (HttpServletRequest request, 
      HttpServletResponse response) { 
    //Get the 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 logical code is mainly as above.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.