实现购物车

一、购物车的实现流程

购物车流程| ProcessOn免费在线作图,在线流程图,在线思维导图

二、创建Book类,封装图书信息

public class Book implements Serializable {
	private static final long serialVersionUID = 1L;
	private String id;  //书的编号
	private String name; //书名

	public Book() {
	}

	public Book(String id, String name) {
		this.id = id;
		this.name = name;
	}
//补上get set

三、创建数据库模拟类BookDB

public class BookDB {
	private static Map<String, Book> books = new LinkedHashMap<String, Book>();
	static {
		books.put("1", new Book("1", "javaweb开发"));
		books.put("2", new Book("2", "jdbc开发"));
		books.put("3", new Book("3", "java基础"));
		books.put("4", new Book("4", "struts开发"));
		books.put("5", new Book("5", "spring开发"));
	}

	// 获得所有的图书
	public static Collection<Book> getAll() {
		return books.values();
	}

	// 根据指定的id获得图书
	public static Book getBook(String id) {
		return books.get(id);
	}
}

四、创建Servlet

1.ListBookServlet

显示所有可购买图书,并提供购买链接

public class ListBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter out = resp.getWriter();
			Collection<Book> books = BookDB.getAll();
			out.write("本站提供的图书有:<br>");
			for (Book book : books) {
				String url = req.getContextPath()+"/addBookToCartServlet?id=" + book.getId();
				out.write(book.getName() + "<a href='" + url 
						+ "'>点击加入购物车</a><br>");
				//String url = req.getContextPath()+"/addBookToCartServlet?id=" + book.getId();
				//String newUrl=resp.encodeURL(url);
				//out.write(book.getName() + "<a href='" + newUrl + "'>点击加入购物车</a><br>");
			}
 
		}
	}

2.AddBookToCartServlet

a.将用户购买的图书放入购物车,购物车保存到Session对象中;

b.重定向到用户已经加入购物车的图书列表;

public class AddBookToCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		// 获得用户要加入购物车的图书id
		String id = req.getParameter("id");
		if (id == null) {
			// 如果id为null,重定向到ListBookServlet页面
			String url = req.getContextPath()+"/listBookServlet";
			resp.sendRedirect(url);
			return;
		}
		Book book = BookDB.getBook(id);
		// 创建或者获得用户的Session对象
		HttpSession session = req.getSession();
		// 从Session对象中获得用户的购物车
		List<Book> cart = (List) session.getAttribute("cart");
		if (cart == null) {
			// 首次购买,为用户创建一个购物车(List集合模拟购物车)
			cart = new ArrayList<Book>();
			// 将购物车存入Session对象
			session.setAttribute("cart", cart);
		}
		// 将商品放入购物车
		cart.add(book);
		// 创建Cookie存放Session的标识号
		Cookie cookie = new Cookie("JSESSIONID", session.getId());
		cookie.setMaxAge(60 * 30);
		cookie.setPath(req.getContextPath());
		resp.addCookie(cookie);
		// 重定向到购物车页面
		String url = req.getContextPath()+"/cartServlet";
 		resp.sendRedirect(url);
		//String newurl = resp.encodeRedirectURL(url);
		//resp.sendRedirect(newurl);
 
	}
}

3.CartServlet

展示用户已经加入购物车的图书

public class CartServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		// 变量cart引用用户的购物车
		List<Book> cart = null;
		// 变量pruFlag标记用户是否加入过图书到购物车
		boolean purFlag = true;
		// 获得用户的session
		HttpSession session = req.getSession(false);
		// 如果session为null,purFlag置为false
		if (session == null) {
			purFlag = false;
		} else {
			// 获得用户购物车
			cart = (List) session.getAttribute("cart");
			// 如果用户的购物车为null,purFlag置为false
			if (cart == null) {
				purFlag = false;
			}
		}
		/*
		 * 如果purFlag为false,表明用户没有加入过图书到购物车,重定向到ListServlet页面
		 */
		if (!purFlag) {
			out.write("对不起!您还没有加入任何图书到购物车!<br>");
            resp.sendRedirect(req.getContextPath()+"/listBookServlet");
		} else {
			// 否则显示用户购物车里图书的信息
			out.write("您购物车里的图书有:<br>");
			for (Book book : cart) {
				out.write(book.getName() + "<br>");
			}
		}
	}
}

五、运行项目,查看结果

http://localhost:8080/javaweb-demo/ListBookServlet

 点击链接加入购物车,结果如下:

 注意:Session ID是保存在Cookie中,Cookie设置了有效时间,那么在有效时间内,即使用户关闭浏览器再打开浏览器,服务器也能收到SessionID,也就能找到Session对象,如果该对象没有失效。

以下是使用JavaWeb中session实现购物车代码示例: 1. 创建商品 ```java public class Product { private int id; // 商品ID private String name; // 商品名称 private double price; // 商品价格 private int quantity; // 商品数量 public Product(int id, String name, double price, int quantity) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; } // setter和getter方法省略 } ``` 2. 创建购物车 ```java import java.util.ArrayList; import java.util.List; public class ShoppingCart { private List<Product> productList; // 商品列表 public ShoppingCart() { productList = new ArrayList<>(); } // 添加商品到购物车 public void addProduct(Product product) { productList.add(product); } // 从购物车中删除商品 public void removeProduct(Product product) { productList.remove(product); } // 获取购物车中的所有商品 public List<Product> getProductList() { return productList; } // 获取购物车中商品的总价 public double getTotalPrice() { double totalPrice = 0; for (Product product : productList) { totalPrice += product.getPrice() * product.getQuantity(); } return totalPrice; } } ``` 3. 在Servlet中使用session实现购物车功能 ```java 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 javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet(name = "ShoppingCartServlet", urlPatterns = "/shoppingCart") public class ShoppingCartServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // 获取购物车对象 ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart"); if (shoppingCart == null) { // 如果session中不存在购物车对象,则创建一个 shoppingCart = new ShoppingCart(); session.setAttribute("shoppingCart", shoppingCart); } // 获取操作型 String action = request.getParameter("action"); // 添加商品到购物车 if ("add".equals(action)) { int productId = Integer.parseInt(request.getParameter("productId")); String productName = request.getParameter("productName"); double productPrice = Double.parseDouble(request.getParameter("productPrice")); int quantity = Integer.parseInt(request.getParameter("quantity")); Product product = new Product(productId, productName, productPrice, quantity); shoppingCart.addProduct(product); response.sendRedirect("productList.jsp"); } // 从购物车中删除商品 if ("remove".equals(action)) { int productId = Integer.parseInt(request.getParameter("productId")); for (Product product : shoppingCart.getProductList()) { if (product.getId() == productId) { shoppingCart.removeProduct(product); break; } } response.sendRedirect("shoppingCart.jsp"); } // 清空购物车 if ("clear".equals(action)) { shoppingCart = new ShoppingCart(); session.setAttribute("shoppingCart", shoppingCart); response.sendRedirect("shoppingCart.jsp"); } } } ``` 4. 在JSP页面中显示购物车信息 ```jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>购物车</title> </head> <body> <h1>购物车</h1> <table border="1"> <thead> <tr> <th>商品ID</th> <th>商品名称</th> <th>商品价格</th> <th>商品数量</th> <th>总价</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="product" items="${sessionScope.shoppingCart.productList}"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.quantity}</td> <td>${product.price * product.quantity}</td> <td> <form action="shoppingCart" method="post"> <input type="hidden" name="action" value="remove" /> <input type="hidden" name="productId" value="${product.id}" /> <input type="submit" value="删除" /> </form> </td> </tr> </c:forEach> <tr> <td colspan="4">总价:</td> <td>${sessionScope.shoppingCart.totalPrice}</td> <td> <form action="shoppingCart" method="post"> <input type="hidden" name="action" value="clear" /> <input type="submit" value="清空购物车" /> </form> </td> </tr> </tbody> </table> <a href="productList.jsp">继续购物</a> </body> </html> ``` 以上就是使用JavaWeb中session实现购物车代码示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值