面向对象中的session版的购物车

本文介绍了一个简单的购物车系统的实现过程,包括Product类用于存储商品信息,ProductDao类使用List集合管理商品,通过ShowProductServlet展示商品信息,AddCarServlet处理商品添加到购物车逻辑,最后由ShowCarServlet展示购物车内的商品及总价。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先设置一个product类,用来存储和获取数据,使用LIst集合存储所有商品即(ProductDao类),在ShowProductServlet类查看商品信息,然后将数据提交到AddCarServlet类来处理数据,最后在ShowCarServlet类查看购物车并显示数量和价格。


程序运行如下图所示:

ShowProductServlet类显示效果

ShowCarServlet类查看购物车


源代码如下:

Product

package star.july.buycar;

public class Product {
	private int id;
	private String name;
	private int price;
	public void setPrice(int price) {
		this.price = price;
	}
	private String descr;
	private int num =1;	//默认值
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getDescr() {
		return descr;
	}
	public void setDescr(String descr) {
		this.descr = descr;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public int getPrice(){
		return price;
	}
	public Product(int id, String name, int price, String descr) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.descr = descr;
	}
	public Product() {
		super();
	}
	
}




ProductDao:

package star.july.buycar;

import java.util.ArrayList;
import java.util.List;

//商品dao类
public class ProductDao {
	//存储所有的商品的集合
	public static List<Product> data = new ArrayList<Product>();
	static{
		data.add(new Product(1,"三星",4500,"Android机皇"));
		data.add(new Product(2,"苹果",5800,"ISO系统,流畅爽快"));
		data.add(new Product(3,"小米",1999,"为发烧而生"));
		data.add(new Product(4,"华为",2888,"强大的研发实力"));
		data.add(new Product(5,"一加",1999,"超高的性价比"));
	}
	
	//返回所有的商品数据
	public List<Product> findAll(){
		return data;
	}
	
	//根据id查找商品
	public Product findById(int id){
		for(Product p:data){
			if(p.getId() == id){
				return p;
			}
		}
		return null;
	}
}


ShowProductServlet:

package star.july.buycar;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

public class ShowProductServlet extends HttpServlet {

	ProductDao dao = new ProductDao();
	 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Product> product = dao.findAll();		//返回Product对象 
		
		//显示中文
		response.setContentType("text/html;charset=utf-8");
		//显示商品列表
		String html ="";
		html += "<html><body>";
		html +="<table border='1' width = 500px>";
		html += "<tr><th>编号</th><th>品牌</th><th>价格</th><th>描述</th><th>购买</th>";
		for(Product p: product){
			html += "<tr><td>"+p.getId()+"</td><td>"+p.getName()+"</td>" +
					"<td>"+p.getPrice()+"</td><td>"+p.getDescr()+"</td>" +
					//getContextPath:获取父目录。 在超链接中传递商品的id,用以添加商品数量
					"<td><a href='"+request.getContextPath()+"/AddCarServlet?id="+p.getId()+"'>购买</a></td>";   
		} 
		html += "</table>";
		html += "</body></html>";
		
		response.getWriter().write(html);
	}
 
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
	}

}



AddCarServlet:

package star.july.buycar;

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

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

public class AddCarServlet extends HttpServlet {
		
	ProductDao dao = new ProductDao();
	 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得ID
		String id = request.getParameter("id");
		//查找商品
		Product product = dao.findById(Integer.parseInt(id)); 
		
		//获取session
		HttpSession session = request.getSession();
		//设计一个集合用以存储购物车中的所有商品数据
		//使用session.getAttribute()是为了判断第一个商品
		Map<Integer,Product> car = (Map<Integer, Product>) session.getAttribute("car");
		//如果是第一个商品,就进行初始化
		if(car == null ){
			car = new HashMap<Integer,Product>();
		}
		if(car != null && car.containsKey(Integer.parseInt(id))){  //判断是否是集合里的key的值 
			Product p = car.get(Integer.parseInt(id)); 			//返回key(id)对应的值
			p.setNum(p.getNum()+1);									//商品数量+1
		}else{
			//没有买过,需要重新加入购物车
			car.put(product.getId(), product);
		}
		//将car的值赋值给属性car,后者给前者
		session.setAttribute("car", car);
	 
		//回显
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(product.getName()+"已成功加入购物车! <a href = '"+request.getContextPath()+"/ShowCarServlet'>查看购物车</a>");
	}

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

}


ShowCarServlet:

package star.july.buycar;

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

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

public class ShowCarServlet extends HttpServlet {

	 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//从HttpSession中取出数据
		HttpSession session = request.getSession();
		Map<Integer,Product> car =(Map<Integer,Product>)session.getAttribute("car");
		
		//显示中文
		response.setContentType("text/html;charset=utf-8");
		String html ="";
		html += "<html><body>";
		html +="<table border='1' width = 500px>";
		html += "<tr><th>编号</th><th>品牌</th><th>价格</th><th>数量</th><th>描述</th><th>小计</th>";
		double totalProduct = 0;		//商品的总价
		for(Entry<Integer,Product> entry : car.entrySet()){
			Product p = entry.getValue(); 
			html += "<tr><td>"+p.getId()+"</td><td>"+p.getName()+"</td>" +
							"<td>"+p.getPrice()+"元</td><td>"+p.getNum()+"</td><td>"+p.getDescr()+"" +
							"</td><td>"+p.getPrice()*p.getNum()+"元</td>";
			totalProduct += p.getPrice()*p.getNum();
		} 
		html += "<tr><td colspan ='6' align='right'>合计:"+totalProduct+"元</td></tr>";
		html += "</table>";
		html += "<p><a href='"+request.getContextPath()+"/ShowProductServlet'>继续购物</a>";
		html += "</body></html>";
		response.getWriter().write(html);
	}

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

		 doGet(request, response);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值