IT俱乐部 Jsp JavaWeb程序设计之JSP实现购物车功能全过程

JavaWeb程序设计之JSP实现购物车功能全过程

一、结合之前所学的相关技术,编写代码实现以下购物车功能

1. 编写一个页面,展现商品列表(静态页面),页面右上方有登陆、结账和查看购物车三个按钮,下方展示网站历史访问的人数

2. 用户点击商品后,可以将商品加入购物车

3. 用户点击登陆,跳转到登陆页面

4. 用户点击结账,若已登陆跳转至结账页面,否则跳转到登陆页面登陆后再跳转到结账页。

5. 用户点击查看购物车按钮,跳转至购物车页面,可查看购物车列表、增加商品数量或者删除商品

1. 我实现的功能运行截图如下

(1)商品列表页面home.jsp

(2)登录账号页面/未登录点击结账页面

(3)重新登录页面(记住上次登录的用户名和密码)

(4)点击任意商品加入购物车之后查看购物车

(5)增加或减少商品

(6)商品数量减为0时移除

(7)点击去结算,展示总金额

2. 数据库test存放的表格

(1)user表

(2)product表

导入jar包 

3. 实体类

(1)User

package com.ryx.web.sy7;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class User {
    private String username;
    private String password;
}

(2)Product.java

package com.ryx.web.sy7;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    Integer id;
    String name;
    String imagePath;
    BigDecimal price;
    String description;
}

(3)ProductVo

package com.ryx.web.sy7;

import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;

public class ProductVo extends Product {
    @Getter
    @Setter
    Integer count; //统计数量

    public ProductVo(Integer id, Integer count, String name, double price, String imagePath) {
        super();
        this.id = id;
        this.count = count;
        this.name = name;
        this.price = BigDecimal.valueOf(price);
        this.imagePath=imagePath;
    }
}

4. CartController.java

package com.ryx.web.sy7;

import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;
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;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "shoppingCart", value = "/shoppingCart")
public class CartController extends HttpServlet {
//    连接数据库
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "abc1234";

    @SneakyThrows
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String op = request.getParameter("op");
        String whereCome = request.getHeader("Referer");
        String redirectPath = null;
//        如果在主页点击加入购物车超链接,不跳转
        if (whereCome.equals("http://localhost:8080/sy7/home.jsp")) {
            redirectPath = request.getContextPath() + "/sy7/home.jsp";
        } else {
//            如果在购物车页面增加或删除商品也不跳转
            redirectPath = request.getContextPath() + "/sy7/cart.jsp";
        }
        HttpSession session = request.getSession();
        Map cart = (Map) session.getAttribute("cart");
        if (ObjectUtils.isEmpty(cart)) {
            cart = new HashMap();
        }
        switch (op) {
//            添加商品
            case "add":
                if (!ObjectUtils.isEmpty(cart.get(id))) {
                    ProductVo productVo = cart.get(id);
                    productVo.setCount(productVo.getCount() + 1);
                    cart.put(id, productVo);
                } else {
                    Class.forName("com.mysql.jdbc.Driver");
                    try (Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD)) {
                        String query = "SELECT * FROM product WHERE id = ?";
                        try (PreparedStatement stmt = conn.prepareStatement(query)) {
                            stmt.setInt(1, id);
                            try (ResultSet rs = stmt.executeQuery()) {
                                if (rs.next()) {
                                    String name = rs.getString("name");
                                    double price = rs.getDouble("price");
                                    String imagePath = rs.getString("image_path");
                                    Integer iid = rs.getInt("id");
                                    ProductVo productVo = new ProductVo(iid, 1, name, price, imagePath);
                                    cart.put(id, productVo);
                                }
                            }
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                break;
//          减少商品
            case "sub":
                if (!ObjectUtils.isEmpty(cart.get(id))) {
                    ProductVo productVo = cart.get(id);
//                    防止出现负数
                    if (productVo.getCount() > 1) {
                        productVo.setCount(productVo.getCount() - 1);
                        cart.put(id, productVo);
                    } else {
//                        如果小于1则移除商品
                        cart.remove(id);
                    }

                }
                break;
        }
        session.setAttribute("cart", cart);
        response.sendRedirect(redirectPath);
    }
}

5. JSP页面

(1)展现商品列表(home.jsp)

CSS

table {
    border-collapse: collapse;
    width: 86%;
}

table, th, td {
    border: 1px solid gainsboro;
}

td {
    width: 200px;
}

.redText {
    color: #FF0000;
}

.pinkTest {
    color: lightpink;
}








    小煊的美妆铺

欢迎来到小煊的美妆铺~


“);
}
%>

“);
}
count++;
}
//最后不足五个,自动闭合
if (count % 5 != 0) {
out.println(“”);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
conn.close();
} catch (Exception e) {
}
}
%>

¥:

历史访问人数:

(2)登陆页面(login.jsp)

JSP程序段+JS代码




    var error = '';
    alert(error);

HTML




    
        body {
            display: flex;
            justify-content: center;
            padding-top: 40px;
        }
        .titlecolor{
            color: lightpink;
        }
    登录页面

登录账号

用户名: ” id=”username” name=”username” required>
” id=”password” name=”password” required>
记住密码

(3)登录后台处理页面(loginAction.jsp)







(4)结账页面(checkout.jsp)

HTML+JSP+JSTL










    结算

订单信息

cart = (Map) session.getAttribute("cart"); if (cart == null) { out.println("购物车为空"); return; } %>

您应支付:¥${totalAmount}

(5)购物车页面(cart.jsp)

CSS

table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid gainsboro;
}

.titleTest {
    color: lightpink;
}

td {
    width: 20%;
}

a {
   text-decoration: none;
}

HTML







    购物车

我的购物车

商品信息 单价 数量 金额
${product.name} ¥:${product.price} ${product.count} ¥:${product.count*product.price}


总结 

到此这篇关于JavaWeb程序设计之JSP实现购物车功能的文章就介绍到这了,更多相关JSP实现购物车功能内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/jsp/14680.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部