The Ultimate Perfect Shopping Cart System Reveals--MVC Design Mode

Simple Shopping System

People often go online to get enough, so the so-called shopping cart on the Internet should not be unfamiliar, so today we use the MVC design mode of javaweb to implement a case of online shopping system.

The results are as follows:

 

A brief introduction to the three-tier architecture

1. Development Steps

First figure out what you want to do, then:

1. Set up development environment

jstl.jar

standard.jar

2. Create Class Packages

3. Set up a database

Use in-memory database

In summary, the implementation of this shopping cart uses MVC design mode, the idea of MVC design mode is to display from jsp--javabean-servlet--jsp page

Flow chart:

 

Figure 1: Introduction to MVC design pattern

Figure 2: Implementing ideas for shopping system cases:

Figure 3: Design the shopping cart page

 

The Festival Officially begins, and you can't miss it.

1. Write a jsp shopping page

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    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> 
    
    <title>Piaoye Online Shop</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">
    -->
  </head>
  
  <body>
  <hr/>
  <h2 >Welcome to Drifting Leaf Online Shopping Mall</h2>
  <hr>
       <a href="${pageContext.request.contextPath}/ListBookServlet">Go to shopping page</a> <br>
  </body>
</html>

2. Write a javabean

package cn.itcast.cart.domain;

public class Book
{
    private String id;
    private String name;//Title
    private String author;//author
    private int price;
    
    public Book()
    {
        super();
        // TODO Auto-generated constructor stub
    }
    public Book(String id, String name, String author, int price)
    {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
    }
    public String getId()
    {
        return id;
    }
    public void setId(String id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getAuthor()
    {
        return author;
    }
    public void setAuthor(String author)
    {
        this.author = author;
    }
    public int getPrice()
    {
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }
    
}

 

3. Set up a DB to simulate a database with a Map collection

package cn.itcast.cart.domain;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class DB
{
//    Use map Collection to simulate database
    private static Map<String , Book> books=new LinkedHashMap<String, Book>();
    static{
        books.put("1", new Book("1", "<Water Margin", "Shi Nai'an", 48));
        books.put("2", new Book("2", "<Journey to the West", "Wu Cheng-en ", 58));
        books.put("3", new Book("3", "<The Romance of the Three Kingdoms", "Luo Guanzhong", 78));
        books.put("4", new Book("4", "<Dream of Red Mansion", "Cao Xueqin", 28));
        books.put("5", new Book("5", "<Ordinary World", "Rotel", 18));
    }
//    Get all books
    // Get all books
    public static Collection<Book> getAll() {
        return books.values();
    }
    
    // according to id Find Books
    public static Book find(String id) {
        return books.get(id);
    }
}

4. Create a shopping cart object with javabean

package cn.itcast.cart.domain;

public class ShoppingcartItem
{
    //Shopping cart items, how many books each book has bought, how much is the total money
    private Book book;
    private int quantity;
    private int price;
    public Book getBook()
    {
        return book;
    }
    public void setBook(Book book)
    {
        this.book = book;
    }
    public int getQuantity()
    {
        return quantity;
    }
    public void setQuantity(int quantity)
    {
        this.quantity = quantity;
        this.price=this.book.getPrice()*quantity;
    }
    public int getPrice()
    {
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }

}

 

Shopping cart - cart

package cn.itcast.cart.domain;

import java.util.HashMap;
import java.util.Map;

//Shopping Cart Objects
public class Shoppingcart
{
    private Map<String, ShoppingcartItem> items=new HashMap<String, ShoppingcartItem>();
    private int price;//Total Price
    public Map<String, ShoppingcartItem> getItems()
    {
        return items;
    }
    public void setItems(Map<String, ShoppingcartItem> items)
    {
        this.items = items;
    }
    public int getPrice()
    {
        //Calculate total price
        int price=0;
        for(ShoppingcartItem item:items.values())
        {
            price+=item.getPrice();
        }
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }
}

5. Obtain a servlet for a list of book merchandises-ListBookServlet.java

package cn.itcast.cart.web.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.cart.domain.Book;
import cn.itcast.cart.domain.DB;

public class ListBookServlet extends HttpServlet
{
    //from DB Query all books in
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //Query all items
        Collection<Book> books = DB.getAll();
//        Forward to jsp display
        request.setAttribute("books", books);
        request.getRequestDispatcher("/WEB-INF/pages/listbook.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

 

6. The data handled by the servlet is forwarded to a page showing the goods-listbook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show all items</title>
<script type="text/javascript">
    function buy(id){
        window.location = "${pageContext.request.contextPath}/BuyServlet?id="+id;
    }
</script>

</head>
<body style="text-align: center">
    <h1 >List of Goods</h1>
    <table border="1"  width="400px">
        <tr>
            <td>Book Name</td>
            <td>author</td>
            <td>Price</td>
            <td>purchase</td>
        </tr>
        <c:forEach var="book" items="${requestScope.books}">
            <tr>
            <td>${book.name}</td>
            <td>${book.author}</td>
            <td>${book.price}</td>
            <td>
                <input type="button" value="purchase" onclick="buy(${book.id})"/>
            </td>
        </tr>
        </c:forEach>
    </table>
</body>
</html>

7. Write a servlet for purchase processing

package cn.itcast.cart.web.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.cart.domain.Book;
import cn.itcast.cart.domain.DB;
import cn.itcast.cart.domain.Shoppingcart;
import cn.itcast.cart.domain.ShoppingcartItem;

public class BuyServlet extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //Purchase Page
        //Get Books
        String id=request.getParameter("id");
        Book book=DB.find(id);
//        Get a shopping cart
        Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart");
        if(cart==null){
            //First time shopping
            cart=new Shoppingcart();
            request.getSession().setAttribute("cart", cart);
        }
//        Goods in shopping cart
        bookInCart(book,cart);
//        Jump to the shopping cart page,Is a page requesting redirection
        response.sendRedirect(request.getContextPath()+"/ListCartServlet");
    }
//Shopping
    private void bookInCart(Book book, Shoppingcart cart)
    {//Determine if you have ever bought
        Map<String, ShoppingcartItem> items = cart.getItems();
        
        ShoppingcartItem item = items.get(book.getId());
        
        if(item==null){
            //This book has not been bought, create a new entry
            item=new ShoppingcartItem();
            item.setBook(book);
            item.setQuantity(1);
            //Entries are stored in the shopping cart
            items.put(book.getId(), item);
        }else{
            //Buied quantity plus 1
            item.setQuantity(item.getQuantity()+1);
        }
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

8. Write a servlet to get data processing from the shopping cart-ListCartServlet.java

package cn.itcast.cart.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListCartServlet extends HttpServlet
{
    
    //View the shopping cart, request redirection page
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        request.getRequestDispatcher("/WEB-INF/pages/listcart.jsp").forward(request, response);
        
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

 

9. Put your purchases in the shopping cart and turn to the shopping cart display page-listcart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%--    As long as you use foreach To import this code--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Shopping Cart Page</title>
<script type="text/javascript">
    function change(id,inputObj){
        var quantity=inputObj.value;

        if(quantity==null || quantity=="") {
            alert("Quantity cannot be empty");
            inputObj.value = defaultValue;
            return;
        }
        
        if(quantity.match(/^[1-9][0-9]*$/)==null) {
            alert("Quantity must be a positive integer");
            inputObj.value = defaultValue;
            return;
        }
        
        if(parseInt(quantity)>999) {
            alert("The quantity you have purchased has reached the group purchase standard, please call 800-820-8820");
            inputObj.value = defaultValue;
            return;
        }
        
        
        window.location="${pageContext.request.contextPath}/UpdateServlet?id="+id+"&quantity="+quantity;
    }
</script>

</head>
<body style="text-align: center">
<h1>My shopping cart</h1><br>
<hr>
<table border="1" width="800px">
    <tr>
        <td>Commodity Name</td>
        <td>Unit Price</td>
        <td>Number</td>
        <td>Subtotal</td>
        <td>operation</td>
    </tr>
<%--map After iteration, all entry--%>
    <c:forEach var="entry" items="${cart.items}">
    <tr>
        <td>${entry.value.book.name}</td>
        <td>${entry.value.book.price}</td>
        <td>
            <input type="text" value="${entry.value.quantity}"  onblur="change(${entry.key},this) " style="width: 40px;"/>
        </td>
        <td>${entry.value.price}</td>
        <td>
            <a href="${pageContext.request.contextPath}/DaleServlet?id=${entry.key }">delete</a>
        </td>
    </tr>    
    </c:forEach>
    <tr>
        <td>
            <a href="${pageContext.request.contextPath}/clearServlet">empty cart</a>
        </td>
        <td>
            <a href="${pageContext.request.contextPath}/ListBookServlet">Continue shopping</a>
        </td>
        <td>
            <a href="#">Place an order</a>
        </td>
        <td colspan="2">Total Shopping Cart Price:¥${cart.price}element</td>
    </tr>
</table>
</body>
</html>

Here are some of the operation functions inside the shopping cart

10. Updating the shopping cart means automatically updating the shopping cart after modifying the quantity-UpdateServlet.java

package cn.itcast.cart.web.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.cart.domain.Shoppingcart;
import cn.itcast.cart.domain.ShoppingcartItem;

public class UpdateServlet extends HttpServlet
{
    //Update shopping cart
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //Get id and quantity
        String id=request.getParameter("id");
        int quantity=Integer.parseInt(request.getParameter("quantity"));
        //Get a shopping cart
        Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart");
        // Modified Quantity
        /*
        Map<String, ShoppingcartItem> items = cart.getItems();
        
        ShoppingcartItem item = items.get(id);
        
        item.setQuantity(quantity);*/
        
        cart.getItems().get(id).setQuantity(quantity);
        
        // Jump to the shopping cart page
        response.sendRedirect(request.getContextPath() + "/ListCartServlet");
    }

        
    

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

11. Delete one-line data from the shopping cart -DaleServlet.java

package cn.itcast.cart.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.cart.domain.Shoppingcart;

public class DaleServlet extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        // Get id
        String id = request.getParameter("id");
        
        // Get a shopping cart
        Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart");
        
        //Delete entries
        cart.getItems().remove(id);

        // Jump to the shopping cart page
        response.sendRedirect(request.getContextPath()+"/ListCartServlet");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

12. Empty the shopping cart-clearServlet.java

package cn.itcast.cart.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.cart.domain.Shoppingcart;

public class clearServlet extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        // Get a shopping cart
        Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart");
        
        // empty cart
        cart.getItems().clear();
        
        // Jump to the purchase page
        response.sendRedirect(request.getContextPath()+"/ListBookServlet");
    }




    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}

 

ok, busy till midnight, that's the end. Let's see what we're doing in the end:

--------------------------------------------------------------------------------------------------

 

 

-------------------------------------------------------------------------------------------------

Hey hey, no artistic pages, okay, like that?

All the above functions can be achieved!

Keywords: Java JSP Database Javascript

Added by NogDog on Fri, 26 Jun 2020 04:41:02 +0300