Realization of java web shopping cart case

Not much nonsense, here is a simple small system of a book shopping cart.

Some pictures of the running results show:
insert image description here
insert image description here

So it is necessary to create an entity class, which should include all the contents of a book, complete its set, get, and construction methods, and call its class Book.java.

Then you need to create a Dome.java to replace the database, which means that the data in this Dome will be used as a database. Then there is the three-tier model of Java web. The Dao Service Servlet here is all simulation, because Dome.java simulates data, so there is no need to connect to the database, because the data in Dome is Book type, So the type of Map<String, Book> is used here, and the data is added using the method of map.put.

The following is the code of the Dao layer that does not require a database, so it is simple here, just create a new method directly.
Create the GetAll() method to obtain the Map collection storing books. Create a find method to obtain a book according to the keyword, that is, the book under a certain id value at the time of acquisition

Because the shopping cart is a whole, there are shopping items in the shopping cart, which can be added or deleted, so create a Cart.java, which is the shopping cart class, and create CartItem.java, which is in the shopping cart Shopping item,
the shopping item should include Book, the quantity of the book, and the price. It should be noted that the price of the five items should be equal to the quantity of the book * the price of the book. Therefore, when supplementing the set and get methods, the method of getPrice should be rewritten.

The shopping cart contains the shopping item and the total price of the shopping cart. Create a map collection Map<String, CartItem> here. The creation method: addBook adds the shopping item to the shopping cart. The creation method: getPrice The total price of the shopping cart is all Add up the prices of the shopping items. When adding Book, it is necessary to determine whether the shopping item exists in the shopping cart. If it does not exist, a new CartItem is required. The book passed by the user is used as a parameter, and the number of shopping items is set to 1. , and then use map.put to add the shopping item to the shopping cart. If the shopping item exists, you only need to add 1 to its quantity setting, and then modify the method of getPrice to add the total value of the shopping cart The price is the sum of the prices of all shopping items

The Service layer is the call to the Dao layer, getAll(), findBook(), adding and purchasing books. buyBook(String id, Cart cart), when you click the add button on the front end, the id of the book will be passed from the sevlet, the servlet calls the service, and the service then calls the dao layer, and the Cart is in the project It was actually clicked once. Then add the book to the shopping cart. Then there is the deletebook method. deletebook(String id, Cart cart) needs to customize the exception class method here, because there is a possibility, that is to say, if your shopping cart is empty, it will directly throw an exception and display Out your cart is empty. Then delete, first get all the shopping items in the shopping cart, then find one of the Strings, and remove it. Empty the shopping cart: clearCart (Cart cart),
just clear it directly with cart.getMap().clear. The quantity of the shopping cart can actually give you a blank bar for you to fill in at will. You need to set it here. Suppose you fill in the books you want to buy, but you cancel the purchase, and then the quantity does not change. The price It has not changed, so the back-end data needs to be updated in time. updateCart(Cart cart,String bookid,int quantity), because the id can only be obtained from the front end, and there is also a cart, so it is still needed here, and the cart, id, and quantity are passed from the front end, and the number can only be obtained from the CartItem modified among.

The last is the connection between the servlet and the front end, which realizes some very common and basic screens. So relatively crude.

This is the Book code to encapsulate it.

package org.awen.enetity;

public class Book {
	private String id;
	private String name;
	private String author;
	private String description;
	private double price;
	public Book(String id, String name, String author, String description, double price) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
		this.price = price;
	}
	public Book() {
		super();
	}
	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 String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", author=" + author + ", description=" + description + ", price="
				+ price + "]";
	}
	
}

Then encapsulated into Dome

package org.awen.enetity;

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

public class Domo {
	static Book book1=new Book("1","java","zhongfucheng","好书",99);
	static Book book2=new Book("2","javaweb","hhhh","不好的书",44);
	static Book book3=new Book("3","ajax","xiaoming","一般般的书",23);
	static Book book4=new Book("4","spring","xiaohong","好书",56);
	private static Map<String ,Book> map=new LinkedHashMap<>();
	
	
	public static Map<String ,Book>getAll(){
		
		map.put("1", book1);
		map.put("2", book2);
		map.put("3", book3);
		map.put("4", book4);
		return map;
		
	}
	/*
	public static void main(String args[]) {
	}
	
	*/
}

Code writing of the Service layer:

package org.awen.service;

import java.util.Map;

import org.awen.dao.BookDao;
import org.awen.enetity.Book;
import org.awen.enetity.Cart;
import org.awen.enetity.CartItem;
import org.awen.exception.CartNotFoundException;

public class BusinessService {
	static BookDao bookDao=new BookDao();
	
	
	/***
	 * 列出来所有的书
	 * 
	 */
	public static Map getAll() {
		return bookDao.getAll();
	}
	
	
	/***
	 * 根据书的id获取书
	 * 
	 * 
	 */
	
	public Book findBook(String id) {
		return bookDao.find(id);
	}
	
	
	/***
	 * 在购买书籍的时候,
	 * 
	 * 
	 * 把用户想买的书籍添加到当前用户的购物车上
	 */
	public void buyBook(String id,Cart cart) {
		Book book=bookDao.find(id);
		cart.addBook(book);
	}
	
	
	/***
	 * 删除购物车中的某一本书籍
	 * @throws CartNotFoundException 
	 * 
	 */
	public void deletebook(String id,Cart cart) throws CartNotFoundException {
		
		if(cart==null) {
			throw new CartNotFoundException("购物车为空");
		}
		
		//把购物项移出去集合就行了  得到这个 Map<String ,CartItem> map  然后从这个map中remove去除掉这个想删除的id
		cart.getMap().remove(id);
	}
	
	
	/***
	 * 清空购物车的东西
	 * @throws CartNotFoundException 
	 * 
	 * 
	 */
	public void clearCart(Cart cart) throws CartNotFoundException {
		if(cart==null) {
			throw new CartNotFoundException("购物车为空!");
			
		}
		cart.getMap().clear();
	}
	
	
	/***
	 * 更新购物车的数目 改变成 可以选择 填空的 
	 * @throws CartNotFoundException 
	 * 
	 */
	public void updateCart(Cart cart,String bookid,int quantity) throws CartNotFoundException {
		
		
		if(cart == null) {
			throw new CartNotFoundException("购物车为空!!");
		}
		CartItem item=cart.getMap().get(bookid);
		item.setQuantity(quantity);
	}
}

The code of the Servlet, here is to display all its shopping items on the JSP

package org.awen.Servlet;

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

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 org.awen.service.BusinessService;

/**
 * Servlet implementation class JSPServlet
 */
@WebServlet("/JSPServlet")
public class JSPServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		/***
		 * 调用service层的方法,获取得到存放书籍的Map集合
		 * 
		 * 
		 */
		BusinessService businessservice=new BusinessService();
		Map books=businessservice.getAll();
		
		
		/***
		 * 存放request域对象中,交给jap页面显示
		 * 
		 */
		request.setAttribute("books", books);
		
		/***
		 * 跳转到jsp页面中
		 * 
		 */
		request.getRequestDispatcher("/WEB-INF/listBook.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

The jsp code to display all books:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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>显示所有书籍</title>
</head>
<body>
	<table border="1px">
		<tr>
			<td>书籍编号</td>
			<td>名称</td>
			<td>作者</td>
			<td>详细信息</td>
			<td>价格</td>
			<td>购买</td>
		</tr>
		
		<c:forEach items="${books}" var="me">
       		<tr>
	            <td>${me.key}</td>
	            <td>${me.value.name}</td>
	            <td>${me.value.author}</td>
	            <td>${me.value.description}</td>
	            <td>${me.value.price}</td>
	            
	            <!-- 把想要买的书籍的id传过去给servelt,不然服务器不知道你想买的是哪一个 -->
	            <td><a href="BuyServlet?bookid=${me.key}">购买</a>
        	</tr>
   		 </c:forEach>
		
	
	
	
	
	
	
	
	
	
	</table>
</body>
</html>

Guess you like

Origin blog.csdn.net/guoguozgw/article/details/100013871