Java Online Book Mall (4) Shopping cart module 1_java

Source: Internet
Author: User

This example for you to share the shopping cart module of the specific code for your reference, the specific contents are as follows

It's not a session, it's not a cookie, it's a table

> Add Shopping items
> Modify the number of shopping items
> Delete Entry
> Bulk deletion of entries
> My shopping cart, that is, by user query entries
> Check the entries

1. Data table


Copy Code code as follows:
Insert INTO ' t_cartitem ' (' Cartitemid ', ' quantity ', ' Bid ', ' uid ', ' by ') VALUES (' b8939fc55131469cab11e3924d40185b ') , 1, ' ce01f15d435a4c51b0ad8202a318dca7 ', ' xxx ', 11;

2.CartItem

public class Cartitem {
 private String cartitemid;//primary key
 private int quantity;//number
 private book book;//entry corresponding figure Book
 private user user;//member
 
 //Add Subtotal method public
 double Getsubtotal () {/*
 * * Use BigDecimal without error
 * Requires that you must use the String type constructor
 /BigDecimal B1 = new BigDecimal (Book.getcurrprice () + "");
 BigDecimal b2 = new BigDecimal (quantity + "");
 BigDecimal B3 = b1.multiply (B2);
 return B3.doublevalue ();
 }

 Public String Getcartitemid () {return
 cartitemid;
 }

 public void Setcartitemid (String cartitemid) {
 this.cartitemid = Cartitemid;
 }

 public int getquantity () {return
 quantity;
 }

 public void setquantity (int quantity) {
 this.quantity = quantity;
 }

 Public book GetBook () {return book
 ;
 }

 public void Setbook (book book) {
 this.book = Book;
 }

 Public User GetUser () {return
 user;
 }

 public void SetUser (user user) {
 this.user = user
 }
}

Small tips: Rounding BigDecimal in Java does not have errors

Add Subtotal method public
double Getsubtotal () {/
 * * * use BigDecimal without error
 * requires that you must use a String type constructor
 . BigDecimal B1 = new BigDecimal (Book.getcurrprice () + "");
 BigDecimal b2 = new BigDecimal (quantity + "");
 BigDecimal B3 = b1.multiply (B2);
 return B3.doublevalue ();
}
 

3. Search Cart entry via user

Each entry in my Cart entry needs to display the price of the book's picture, which means that multiple table queries are required.

Public list<cartitem> Findbyuser (string uid) throws SQLException {
 String sql = ' SELECT * from T_cartitem C, t_ Book B where C.bid=b.bid and uid=? ORDER by C.orderby ";
 list<map<string,object>> maplist = qr.query (sql, New Maplisthandler (), UID);
 Return Tocartitemlist (maplist);
}

4. Add Shopping cart Entry----increase

Jsp

<div class= "Divform" >
 <form id= "Form1" action= "<c:url value= '/cartitemservlet '/>" method= "POST" >
 <input type= "hidden" name= "method" value= "Add"/> <input type= "hidden" "name="
 bid "value=" ${ Book.bid} "/>
 I want to buy: <input id=" cnt style= "Width:40px;text-align:center" type= "text" name= "Quantity" value= "1"/> pieces
 </form>
 <a id= "btn" href= "javascript:$" (' #form1 '). Submit (); " ></a>
</div>

Cartitemservlet

Public String Add (httpservletrequest req, HttpServletResponse resp)
 throws Servletexception, IOException {
 /*< c3/>* 1. Encapsulates the form data to Cartitem (bid, quantity)
 /
 Map map = Req.getparametermap ();
 Cartitem Cartitem = Commonutils.tobean (map, cartitem.class);
 Book book = Commonutils.tobean (map, book.class);
 User user = (user) req.getsession (). getattribute ("Sessionuser");
 Cartitem.setbook (book);
 Cartitem.setuser (user);
 Cartitemservice.add (cartitem);
 Return Mycart (req, resp);
}

Cartitemservice

public void Add (Cartitem cartitem) {
 try {
 * * * 1. Use UID and bid to query the database for the existence of this entry
 * *
 cartitem _cartitem = Cartitemdao.findbyuidandbid (
 cartitem.getuser (). Getuid (),
 Cartitem.getbook (). Getbid ());
 if (_cartitem = null) {//If there is no such entry, add the entry
 Cartitem.setcartitemid (Commonutils.uuid ());
 Cartitemdao.addcartitem (Cartitem);
 } else {//If this entry originally existed, modify the quantity
 //Use the original quantity and the number of new entries to make the new quantity
 int quantity = Cartitem.getquantity () + _ Cartitem.getquantity ();
 Modify the number of this old entry
 cartitemdao.updatequantity (_cartitem.getcartitemid (), quantity);
 }
 catch (Exception E) {
 throw new RuntimeException (e);
 }
}

Cartitemdao

public void Addcartitem (Cartitem cartitem) throws SQLException {
 String sql = ' INSERT into T_cartitem (Cartitemid, Quan tity, bid, UID) "+
 " values (?,?,?,?) ";
 Object[] params = {Cartitem.getcartitemid (), cartitem.getquantity (),
 Cartitem.getbook (). Getbid (), Cartitem.getuser (). Getuid ()};
 Qr.update (sql, params);

5. Shopping Cart module page javascript----check

Calculate totals

Add Click event to select All

Add the Click event to the check boxes for all entries

Add a click event to a minus sign

Add the Click event to the plus sign

Bulk Delete

list.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib prefix= "C" uri= "http://" Java.sun.com/jsp/jstl/core "%> <%@ taglib prefix=" FN "uri=" http://java.sun.com/jsp/jstl/functions "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

tips:js in rounded round.js

5. Displays the totals on the total element
$ ("#total"). Text (Round (total, 2));//round () function is to retain the sum of 2 bits


6. Bulk deletion function----Delete

Jsp

function Batchdelete () {
 //1. Gets the checkbox//2 for all selected entries.
 creates an array that adds the values of all selected checkboxes to the array
 //3. Specifies location as Cartitemservlet, parameter method=batchdelete, parameter cartitemids= array's tostring ()
 var cartitemidarray = new Array () ;
 $ (": Checkbox[name=checkboxbtn][checked=true]"). each (the function () {
  Cartitemidarray.push ($ (this). Val ());// Add the value of the check box to the array
 });
 Location = "/goods/cartitemservlet?method=batchdelete&cartitemids=" + Cartitemidarray;
}

Delete a

if (quantity = 1) {
 if (confirm) ("Do you really want to delete this entry?") ")) {
  location ="/goods/cartitemservlet?method=batchdelete&cartitemids= "+ ID;
 }
} else {
 

7. Revise quantity----change 

Jsp

Request server, modify quantity.
function sendupdatequantity (ID, quantity) {
 $.ajax ({
 async:false,
 cache:false,
 URL: "/goods/ Cartitemservlet ",
 data:{method:" Updatequantity ", cartitemid:id,quantity:quantity},
 type:" POST "
 , DataType: "JSON",
 success:function (result) {
 //1. Modify Quantity
 $ ("#" + ID + "Quantity"). Val (result.quantity);
 2. Modify Subtotal
 $ ("#" + ID + "Subtotal"). Text (result.subtotal);
 3. Recalculate totals
 showtotal ();}
 }
 );

Servlet

Public String updatequantity (httpservletrequest req, HttpServletResponse resp)
 throws Servletexception, IOException {
 String cartitemid = Req.getparameter ("Cartitemid");
 int quantity = Integer.parseint (Req.getparameter ("Quantity"));
 Cartitem Cartitem = cartitemservice.updatequantity (cartitemid, quantity);
 
 Returns a JSON object to
 the client StringBuilder sb = new StringBuilder ("{");
 Sb.append ("\" quantity\ ""). Append (":"). Append (Cartitem.getquantity ());
 Sb.append (",");
 Sb.append ("\" Subtotal\ ""). Append (":"). Append (Cartitem.getsubtotal ());
 Sb.append ("}");
 
 Resp.getwriter (). print (SB);
 return null;
}

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.