【JavaWeb 小作业】购物车01

需求:使用session实现添加购物车功能

实现:

  1. 首先创建一个实物类,包括ID,书名,老师,单价,数量
  2. 创建添加界面和购物车界面
  3. 实现后台服务器添加serlvet程序

目录结构:
在这里插入图片描述

购物车界面:ShoppingCar:

<%@ page import="bean.ShoppingBean"%>
<%@ page import="java.util.ArrayList"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>购物车</title>
</head>
<body style="text-align: center;">
	<H1>购物车</H1>
	<table border="1" align="center">
		<tr>
			<td width="100px" align="center">课程</td>
			<td width="100px" align="center">老师</td>
			<td width="100px" align="center">单价</td>
			<td width="100px" align="center">数量</td>
		</tr>
		<%
            request.setCharacterEncoding("utf-8");
			ArrayList<ShoppingBean> beans =   (ArrayList<ShoppingBean>)session.getAttribute("list");
			if (beans == null){
			    out.println("    <tr>\n " +
			                "      <td width=\"100px\" align=\"center\"  colspan='4' >购物车为空</td>\n" +
			                "    </tr>");
			}
			else {
			    for (ShoppingBean bean : beans) {
			        String course = bean.getCourse();
			        String teacher = bean.getTeacher();
			        Double price = bean.getPrice();
			        int num = bean.getNum();
			        out.println("    <tr>\n" +
			                    "      <td width=\"100px\" align=\"center\" >" + course + "</td>\n" +
			                    "      <td width=\"100px\" align=\"center\" >" + teacher + "</td>\n" +
			                    "      <td width=\"100px\" align=\"center\" >" + price + "</td>\n" +
			                    "      <td width=\"100px\" align=\"center\" >" + num + "</td>\n" +
			                    "    </tr>");
			    }
			}
		%>
	</table>
</body>
</html>

添加购物界面addShopping:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>添加购物车</title>
    </head>
    <body style="text-align: center;">
      <h1 style="color: red">添加购物车</h1>
      <hr>
      <form action="AddShoppingServlet" name="regform" method="post">
        <table align="center">
          <tr>
            <td>课程:</td>
            <td><input type="text" name="course"/></td>
          </tr>
          <tr>
            <td>老师:</td>
            <td><input type="text" name="teacher"/></td>
          </tr>
          <tr>
            <td>单价:</td>
            <td><input type="text" name="price"/></td>
          </tr>
          <tr>
            <td>数量:</td>
            <td><input type="text" name="num"/></td>
          </tr>
          <tr>
            <td colspan="2"><input type="submit" value="添加购物车" name="添加"/></td>
          </tr>
          
        </table>
      </form>
    </body>
  </html>

后台服务器AddShoppingServlet程序:

package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;

import bean.ShoppingBean;

/**
 * Servlet implementation class AddShoppingServlet
 */
public class AddShoppingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddShoppingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//设置编码格式
		 resp.setContentType("text/html,charset=utf-8");
		 HttpSession session = req.getSession();
        //获取输入的图书信息
        String course = req.getParameter("course");
        String teacher = req.getParameter("teacher");
        String price = req.getParameter("price");
        String num = req.getParameter("num");
        //
        ArrayList<ShoppingBean> shoppingBeans = (ArrayList<ShoppingBean>) session.getAttribute("list");

        ArrayList<ShoppingBean> resultBeans = new ArrayList<>();
        if (shoppingBeans != null){
            resultBeans = shoppingBeans;
        }
        //
        ShoppingBean shoppingBean = new ShoppingBean();
        
        //设置购物车图书信息
        shoppingBean.setId(resultBeans.size());
        shoppingBean.setCourse(course);
        shoppingBean.setTeacher(teacher);
        shoppingBean.setPrice(Double.valueOf(price));
        shoppingBean.setNum(Integer.valueOf(num));
        //添加到购物车
        resultBeans.add(shoppingBean);
        //
        session.setAttribute("list", resultBeans);

        resp.sendRedirect(req.getContextPath() + "/shoppingCar.jsp");
		
		
	}

	/**
	 * @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);
	}

}

实物类ShoppingBean:

package bean;

public class ShoppingBean {
    
    private int id;
    private String course;
    private String teacher;
    private Double price;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getCourse() {
        return course;
    }
    
    public void setCourse(String course) {
        this.course = course;
    }
    
    public String getTeacher() {
        return teacher;
    }
    
    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }
    
    public Double getPrice() {
        return price;
    }
    
    public void setPrice(Double price) {
        this.price = price;
    }
    
    public int getNum() {
        return num;
    }
    
    public void setNum(int num) {
        this.num = num;
    }
    
    private int num;
    
}

演示:
1、第一次进入购物车:
在这里插入图片描述
2、进入添加界面,添加
在这里插入图片描述
3、添加成功
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现一个简单的购物车,可以按照以下步骤: 1. 创建一个商品类,定义商品的属性(如商品ID、名称、价格等)。 2. 创建一个购物车类,定义购物车的属性和方法(如添加商品、删除商品、计算总价等)。 3. 在jsp页面,通过表单向服务器发送请求,将商品添加购物车。 4. 在服务器端,通过servlet接收请求,将商品添加购物车。 5. 在购物车页面,展示购物车的商品信息和总价。 下面是一个简单的实现示例: 商品类: ``` public class Product { private int id; private String name; private double price; // 构造方法和get/set方法省略 } ``` 购物车类: ``` public class ShoppingCart { private Map<Integer, Product> products = new HashMap<>(); // 添加商品 public void addProduct(Product product) { if (products.containsKey(product.getId())) { Product p = products.get(product.getId()); p.setCount(p.getCount() + 1); } else { products.put(product.getId(), product); product.setCount(1); } } // 删除商品 public void removeProduct(int productId) { if (products.containsKey(productId)) { Product p = products.get(productId); if (p.getCount() > 1) { p.setCount(p.getCount() - 1); } else { products.remove(productId); } } } // 计算总价 public double getTotalPrice() { double totalPrice = 0; for (Product p : products.values()) { totalPrice += p.getPrice() * p.getCount(); } return totalPrice; } // 获取购物车的商品列表 public List<Product> getProductList() { return new ArrayList<>(products.values()); } } ``` jsp页面: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>购物车</title> </head> <body> <h1>购物车</h1> <form action="addProduct" method="post"> <label for="productId">商品ID:</label> <input type="text" id="productId" name="productId"><br> <label for="productName">商品名称:</label> <input type="text" id="productName" name="productName"><br> <label for="productPrice">商品价格:</label> <input type="text" id="productPrice" name="productPrice"><br> <input type="submit" value="添加"> </form> <hr> <h2>购物车列表</h2> <table border="1"> <tr> <th>ID</th> <th>名称</th> <th>数量</th> <th>单价</th> <th>小计</th> <th>操作</th> </tr> <c:forEach items="${productList}" var="p"> <tr> <td>${p.id}</td> <td>${p.name}</td> <td>${p.count}</td> <td>${p.price}</td> <td>${p.price * p.count}</td> <td><a href="removeProduct?productId=${p.id}">删除</a></td> </tr> </c:forEach> <tr> <td colspan="4">总价:</td> <td>${totalPrice}</td> <td></td> </tr> </table> </body> </html> ``` servlet: ``` public class ShoppingCartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.parseInt(request.getParameter("productId")); String name = request.getParameter("productName"); double price = Double.parseDouble(request.getParameter("productPrice")); Product product = new Product(id, name, price); ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart"); if (cart == null) { cart = new ShoppingCart(); request.getSession().setAttribute("cart", cart); } cart.addProduct(product); response.sendRedirect("cart.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.parseInt(request.getParameter("productId")); ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart"); if (cart != null) { cart.removeProduct(id); } response.sendRedirect("cart.jsp"); } } ``` 在这个示例,我们使用了一个Map来存储购物车的商品,商品的ID作为Map的键,商品对象作为Map的值。向购物车添加商品时,如果该商品已经在购物车,则将该商品的数量加1;否则将该商品添加购物车,并将数量设置为1。从购物车删除商品时,如果该商品数量大于1,则将数量减1;否则将该商品从购物车删除购物车页面,我们使用了JSTL标签库来展示商品列表和总价。在servlet,我们通过getParameter方法获取表单提交的数据,将商品添加购物车,并将购物车对象放入session。从购物车删除商品时,我们也是从session获取购物车对象,并调用removeProduct方法将商品从购物车删除。最后,我们使用sendRedirect方法重定向到购物车页面,展示购物车的商品列表和总价。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌上人如玉এ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值