Do a hands-on JSP starter program (IX): basic implementation of Shopping cart (Servlet)

Source: Internet
Author: User
Tags button type set set stub
Shopping cart class and shopping cart DAO Shopping Cart

The class is also a JavaBean, with the exception of ordinary getter and setter, where a way to get the total cost of a single book is achieved. We use a book object as the key, to the corresponding number of books for the value of HashMap store all the books in the shopping. This will effectively represent the books in the shopping cart and their number.
Entiry. Cart.java

Package entity;

Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Set;

public class Cart {
//  There will be a lot of merchandise in the car, so we can store it with a map
//  product collection
    private Hashmap<book, Integer > Books;

    Public Cart () {} public

    Hashmap<book, integer> getbooks () {return books
        ;
    }

    public void Setbooks (Hashmap<book, integer> Books) {
        this.books = books;
    }

    public double Getonetypebookcostincart [book book] {return
        book.getprice () * Books.get (book)}
}
Shopping Cart DAO

The necessary analysis of the operation logic, we can know that Userdao need to have the following methods: To determine whether the shopping cart has been selected books, used to determine the insertion of data or update Data add book delete book get user cart

In the shopping cart, we identify a book by UID and ISBN, and determine whose shopping cart and which book it is. In adding a book, we need to determine whether the book is already in the cart, update the data, or insert a record.

DAO. Cartdao.java

Package DAO;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import Java.util.HashMap; Import entity.
Book; Import entity.
Cart; Import util.

DBHelper;
        public class Cartdao {//Judge if the book is already public string isexist (String uid, string ISBN) {Connection conn = null;
        PreparedStatement prestmt = null;
        ResultSet userset = null;
        System.out.println ("Add book"); try{conn = dbhelper.getconnection ()//Determine whether the commodity already exists String sql = "SELECT * FROM Cart wher E uid=?
            and isbn=? ";
            prestmt = conn.preparestatement (sql);
            Prestmt.setstring (1, UID);
            Prestmt.setstring (2, ISBN);

            Userset = Prestmt.executequery ();
            if (Userset.next ()) {return "true";
        Return "false";
            }catch (Exception ex) {ex.printstacktrace ();
        return "error";
  }finally{          if (prestmt!= null) {try {prestmt.close ();
                prestmt = null; 
                catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
        "}}//Add commodity public boolean Addbook (String uid, string ISBN, int num) {
        Connection conn = null;
        PreparedStatement prestmt = null;
        ResultSet userset = null;
        System.out.println ("Add book");
            try{conn = dbhelper.getconnection ()//Determine whether the commodity already exists String exist = isexist (uid, ISBN);
            if (exist = = "Error") {return false;
                }if (exist = = "false") {String sql = "INSERT INTO cart (UID, ISBN, Num) values (?,?,?)";
                prestmt = conn.preparestatement (sql);
            Prestmt.setint (3, num); }else if (exist = = "true") {String sql = "U"Pdate cart set num=num+1 where uid=?
                and isbn=? ";
            prestmt = conn.preparestatement (sql);
            } prestmt.setstring (1, UID);
            Prestmt.setstring (2, ISBN);
            int affectedrownum = Prestmt.executeupdate ();
            if (Affectedrownum > 0) {return true;
            } else{return false;
            }}catch (Exception ex) {ex.printstacktrace ();
        return false;
                    }finally{if (prestmt!= null) {try {prestmt.close ();
                prestmt = null; 
                catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
        }}//Add a commodity public boolean addonebook (String uid, string ISBN) {
        System.out.println ("Add a book");
    Return Addbook (UID, ISBN, 1); }//Delete commodity public boolean deLetebook (String uid, string ISBN) {Connection conn = null;

        PreparedStatement prestmt = null;
            try{conn = Dbhelper.getconnection (); String sql = "Delete from cart where uid=?"
            and isbn=? ";
            prestmt = conn.preparestatement (sql);
            Prestmt.setstring (1, UID);

            Prestmt.setstring (2, ISBN);

            int affectedrownum = Prestmt.executeupdate ();
            if (Affectedrownum < 1) {return false;
        return true;
            }catch (Exception ex) {ex.printstacktrace ();
        return false;
                    }finally{if (prestmt!= null) {try{prestmt.close ();
                prestmt = null;
                }catch (Exception ex) {ex.printstacktrace ();
        //Get user Shopping cart public cart Getcart (String uid) {Connection conn = null; PreparedstatemENT prestmt = null;
        ResultSet bookset = null;
        CART cart = NULL;
            try{conn = Dbhelper.getconnection ();
            String sql = "Select B.name, B.ISBN, B.price, c.num from book B, Cart C where b.isbn = c.isbn and C.uid =?";
            prestmt = conn.preparestatement (sql);
            Prestmt.setstring (1, UID);
            Bookset = Prestmt.executequery ();
            Hashmap<book, integer> books = new Hashmap<book, integer> ();
            Double tolalcost = 0;

                while (Bookset.next ()) {Book book = new book ();
                Book.setname (bookset.getstring ("name"));
                BOOK.SETISBN (Bookset.getstring ("ISBN"));
                float Price = Bookset.getfloat ("price");
                Book.setprice (price);
                int num = Integer.parseint (bookset.getstring ("num"));
                Books.put (book, num);
            Tolalcost + + = Price * NUM;
      Cart = new cart ();      Cart.setbooks (books);
            Cart.settotalcost (Tolalcost);
        return cart;
            }catch (Exception ex) {ex.printstacktrace ();
        return null;
                    }finally{if (bookset!= null) {try{bookset.close ();
                Bookset = null;
                }catch (Exception ex) {ex.printstacktrace ();
                    } if (prestmt!= null) {try{prestmt.close ();
                prestmt = null;
                }catch (Exception ex) {ex.printstacktrace ();
 }
            }
        }
    }
}
Add Product front-end modifications and AJAX requests

We click on the [Add to Cart] button, the Web page will asynchronously request the server via Ajax, and then display the message as a modal box (success or failure) based on the data returned by the server. In order to satisfy this function, we need to modify the index.jsp code, the previous code save for index-before.jsp.

<%@ page language= "java" import= "java.util.*" contenttype= "text/html; Charset=utf-8 "pageencoding=" utf-8 "%> <%@ page import=" entity. Book "%> <%@ page import=" DAO.
        Bookdao "%> <%@ include file=" header.jsp "%> <div class=" main "> <!--modal box (Modal)--> <div class= "Modal Fade id=" Addalert "tabindex="-1 "role=" dialog "aria-labelledby=" Mymodallabel "aria-hidden=" true
                    "> <div class=" Modal-dialog modal-sm "> <div class=" modal-content "> <div class= "Modal-header" > <button type= "button" class= "Close" data-dismiss= "Moda L "aria-hidden=" true ">x</button> 

In addition to adding a modal box, the modification of the button is very important. The button is saved by data in the corresponding book ISBN.

<button class= "add-btn" data-book-isbn= "<%= book.getisbn ()%>" >add to Cart</button>

The following is the code that requests the server asynchronously when the button is clicked. This is the same as all of the other Ajax asynchronous programming. Note the path to submit is:/simpleshop/cart. In the data we submit, there are two fields, which are the ISBN and action type actions, where different submission uid,uid can be obtained in the session. Modal is a method of bootstrap frame modal box, Here is a modal box with ID Addalert displayed. The time to think about is: How to return the data backstage.

Add books to Cart
$ (". Add-btn"). Click (function () {
    var ISBN = $ (this). Data ("BOOK-ISBN");
    $.ajax ({
        URL: "/simpleshop/cart",
        type: "Get",
        DataType: "JSON",
        data: {
            ISBN:ISBN,
            action : "Add"
        },
        success:function (Result) {
            $ (' #addAlert-content '). Text (result.message);
            $ (' #addAlert '). Modal (' show ');
        },
        error:function (Result) {
            $ (' #addAlert-content '). Text ( Result.message);
            $ (' #addAlert '). Modal (' Show ');}});
servlet processing request output, returning to Ajax via PrintWriter

Here for the front-end asynchronous request, you just need to pass the data through the PrintWriter to return the data through the flow. The code snippet is formatted as follows. The contents of the print are returned in JSON format to return an object type to the front end. As a result of a click to add a book, so long as the call Cartdao Addonebook method, for deletion, we just call the Deletebook method. Does it feel like encapsulating a cartdao, and then writing code is a lot easier.

      ensure that the returned data is not garbled
response.setcharacterencoding ("Utf-8");
PrintWriter out = Response.getwriter ();
if (user = null) {
//      not logged
in///      in JSON format return
    out.print ("{\" err\: \ "error\", \ "message\": \ "You are not logged in \}" );  
    Out.flush ();  
    Out.close ();
    return;
}

servlet. Cart.java

Package servlet;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; Import DAO.
Cartdao; Import entity.

User; /** * Servlet Implementation class CART */@WebServlet ("/cart") public class Cart extends HttpServlet {private stat

    IC final long serialversionuid = 1L;
        /** * @see httpservlet#httpservlet () * */Public Cart () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTTPSERVL Etresponse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Ser
        Vletexception, ioexception {User user = (user) request.getsession (). getattribute ("user");//Ensure that the returned data is not garbled
Response.setcharacterencoding ("Utf-8");        PrintWriter out = Response.getwriter ();  
            if (user = null) {//Not logged in Out.print ("{\" err\: \ "error\", \ "message\": \ "You are not logged in \}");  
            Out.flush ();
            Out.close ();
        Return
        String ISBN = Request.getparameter ("ISBN");

        String action = request.getparameter ("action");

        String uid = User.getuid ();
            if (Action.equals ("add")) {Cartdao Cartdao = new Cartdao ();
            if (Cartdao.addonebook (UID, ISBN)) {out.print ("{\" message\ ": \" add success \ "}");
            }else{out.print ("{\" message\ ": \" Add failed \ "}");
            }}else if (action.equals ("delete")) {Cartdao Cartdao = new Cartdao ();
            if (Cartdao.deletebook (UID, ISBN)) {out.print ("{\ err\": \ "Success\", \ "message\": \ "delete successful \"});
            }else{out.print ("{\ err\": \ "fail\", \ "message\": \ "Delete failed \"});  
  } out.flush ();      Out.close ();
     There is no operation}/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcepti
    on {//TODO auto-generated Method stub doget (request, response); }

}
Show Car

The goods in the shopping cart are only displayed when the user logs on, so it is also necessary to use the user in session to judge whether the users have logged in and to make different processing according to different states. Since HashMap cannot traverse, it is necessary to remove the set set of the key value in it, traversing the collection using the Get method to implement the traversal of the HashMap. Note here that the data on the delete, because we also need to use Ajax to implement the deletion, so in order to facilitate the operation of the need to use data to save the ISBN, and because the deletion of a book, the total price needs to be updated, minus so here also use data to save the total cost of each book So as long as you get down a minus on it.
cart.jsp

<%@ page language= "java" import= "java.util.*" contenttype= "text/html" Charset=utf-8 "pageencoding="
    UTF-8 "%>
<%@ page import=" DAO. Cartdao "%>
<%@ page import= entity.*"%> <%@ include file= "header.jsp"%> <div "class=
    " Main Main-white ">
        <!--modal box (Modal)-->
        <div class=" Modal fade "id=" DeleteAlert "tabindex="-1 "
Related Article

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.