This article shares the specific code of the javaweb shopping cart case for your reference. The specific content is as follows
1. Project directory structure
2. Source code
Package--dao layer: BookDao.java
package com.dao;import java.util.Map;import com.DB.DB;import com.domain.Book;public class BookDao { public Map getAll(){ return DB.getAll(); } public Book find(String id){ return (Book) DB.getAll().get(id); }}DB package: DB.java - simulated database
package com.DB;import java.util.LinkedHashMap;import java.util.Map;import com.domain.Book;import com.sun.org.apache.bcel.internal.generic.NEW;//Represents the database//Represents the database public class DB { private static Map map = new LinkedHashMap(); static{ map.put("1", new Book("1","javaweb development","Lao Zhang",38,"a good book")); map.put("2","new Book("2","jdbc development","Lao Li",18,"a good book")); map.put("3", new Book("3","ajax development","Lao Tong",328,"a good book")); map.put("4", new Book("4","jbpm development","Lao Bi",58,"a good book")); map.put("5", new Book("5","struts development","Lao Fang",28,"a good book")); map.put("6", new Book("6","spring development","Lao Fang",98,"a good book")); } public static Map getAll(){ return map; } }domain package:
Book.java: Entity class of a book
package com.domain;//The entity class of the book public class Book { private String id; private String name; private String author; private double price; private String description; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, double price, String description) { super(); this.id = id; this.name = name; this.author = author; this.price = price; this.description = description; } 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 double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }Cart.java: Shopping cart class
package com.domain;import java.util.LinkedHashMap;import java.util.Map;//Shopping cart representing the user//Shopping cart representing the user public class Cart { private Map<String,CartItem> map = new LinkedHashMap(); private double price; //Remember how much all the items in the shopping cart cost public void add(Book book){ //See if there is any in the shopping cart, and the shopping item corresponding to the book to be added CartItem item = map.get(book.getId()); if(item==null){ item = new CartItem(); item.setBook(book); item.setQuantity(1); map.put(book.getId(), item); }else{ item.setQuantity(item.getQuantity()+1); } } public Map<String, CartItem> getMap() { return map; } public void setMap(Map<String, CartItem> map) { this.map = map; } public double getPrice() { double totalprice = 0; for(Map.Entry<String, CartItem> entry : map.entrySet()){ CartItem item = entry.getValue(); totalprice += item.getPrice(); } this.price = totalprice; return price; } public void setPrice(double price) { this.price = price; }}CartItem.java: Shopping Item
package com.domain;//Used to represent a certain product and the number of times it appears (shopping items) public class CartItem { private Book book; private int quantity; private double 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() * this.quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }}service package: service layer
BusinessService.java:
package com.service;import java.util.Map;import com.dao.BookDao;import com.domain.Book;import com.domain.Cart;import com.domain.CartItem;//Business class, provide all services to the web layer in a unified manner public class BusinessService { private BookDao dao = new BookDao(); public Map getAllBook(){ return dao.getAll(); } public Book findBook(String id){ return dao.find(id); } //Delete shopping items in the shopping cart public void deleteCartItem(String id, Cart cart) { cart.getMap().remove(id); } //Clear the shopping cart public void clearCart(Cart cart) { cart.getMap().clear(); } //Change the quantity of shopping items public void changeItemQuantity(String id, String quantity, Cart cart) { CartItem item = cart.getMap().get(id); item.setQuantity(Integer.parseInt(quantity)); } }Web layer:
ListBookServlet.java: Show all books
package com.web.controller;import java.io.IOException;import java.io.PrintWriter;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.service.BusinessService;//Get all books//Get all books public class ListBookServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BusinessService service = new BusinessService(); Map map = service.getAllBook(); request.setAttribute("map", map); request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}BuyServlet.java: Processing purchase requests
package com.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.domain.Book;import com.domain.Cart;import com.service.BusinessService;//Complete book purchase//Complete book purchase public class BuyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); BusinessService service = new BusinessService(); Book book = service.findBook(id); //Get the user's shopping cart Cart = (Cart) request.getSession().getAttribute("cart"); if(cart==null){ cart = new Cart(); request.getSession().setAttribute("cart", cart); } //Add the book to the user's shopping cart and complete the purchase of cart.add(book); //response.sendRedirect("/WEB-INF/jsp/listcart.jsp"); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}DeleteItemServlet.java: Delete a certain product
package com.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.domain.Cart;import com.service.BusinessService;//Delete the specified shopping item public class DeleteItemServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.deleteCartItem(id,cart); //Delete successfully request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}ClearCartServlet.java: Clear the cart
package com.web.controller;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.domain.Cart;import com.service.BusinessService;//Clear the shopping cart public class ClearCartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.clearCart(cart); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}ChangeQuantityServlet.java: Modify the quantity of specified products in the shopping cart
package com.web.controller;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.domain.Cart;import com.service.BusinessService;//Modify the book in the shopping cart to a specified quantity public class ChangeQuantityServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); String quantity = request.getParameter("quantity"); Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessService service = new BusinessService(); service.changeItemQuantity(id,quantity,cart); request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}jsp page:
WebRoot/WEB-INF/jsp/listbook.jsp: Show book list
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Book List Page</title> </head> <body style="text-align: center"> <h1>Book List</h1> <table> <ttr> <td>Book Title</td> <td>Author</td> <td>Selling Price</td> <td>Description</td> <td>Operation</td> </tr> <c:forEach var="entry" items="${map}"> <tr> <td>${entry.value.name }</td> <td>${entry.value.author }</td> <td>${entry.value.price }</td> <td>${entry.value.description } </td> <td> <a href="${pageContext.request.contextPath }/servlet/BuyServlet?id=${entry.value.id }" rel="external nofollow" target="_blank">Buy</a> </td> </tr> </c:forEach> </table> </body>WebRoot/WEB-INF/jsp/listcart.jsp: Show shopping cart list
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Car List</title> <script type="text/javascript"> function deleteitem(id){ var b = window.confirm("Do you confirm the delete??"); if(b){ window.location.href="${pageContext.request.contextPath }/servlet/DeleteItemServlet?id=" rel="external nofollow" +id; } } function clearcart(){ var b = window.confirm("Did you confirm clearing??"); if(b){ window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet" rel="external nofollow" ; } } function changeQuantity(input,id,oldvalue){ var quantity = input.value; //Get the number to be modified sdfsfs /* //Check whether the number of user input is a number if(isNaN(quantity)){ alert("Please enter the number!!"); input.value = oldvalue; return; } */ //Check whether the number of user input is a positive integer if(quantity<0 || quantity!=parseInt(quantity)){ alert("Please enter the positive integer!!"); input.value = oldvalue; return; } var b = window.confirm("You confirm that the number of books is modified to:" + quantity); if(b){ window.location.href="${pageContext.request.contextPath}/servlet/ChangeQuantityServlet?id=" rel="external nofollow" + id + "&quantity=" + quantity; } } </script> </head> <body style="text-align: center"> <h1>Shopping cart list</h1> <c:if test="${empty(cart.map)}"> You did not buy any items! ! ! </c:if> <c:if test="${!empty(cart.map)}"> <table> <tr> <td> <td>Book title</td> <td>Author</td> <td>Unit price</td> <td>Quantity</td> <td>Subtotal</td> <td>Operation</td> </td> <c:forEach var="entry" items="${cart.map}"> <tr> <td>${entry.value.book.name }</td> <td>${entry.value.book.author }</td> <td>${entry.value.book.price }</td> <td> <input type="text" name="quantity" value="${entry.value.quantity }" onchange="changeQuantity(this,${entry.key},${entry.value.quantity})"> </td> <td>${entry.value.price }</td> <td> <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" onclick="deleteitem(${entry.key })">Delete</a> <!-- Remove the default behavior of hyperlinks--> </td> </tr> </c:forEach> <ttr> <td colspan="3">Total price</td> <td colspan="2">${cart.price } Yuan</td> <td colspan="1"> <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" onclick="clearcart()">Clear the cart</a> </td> </tr> </table> </c:if> </body></html>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.