用JavaEE实现购物车

id是指浏览过的商品id 

public class Product {

    private String id;

    private String name;

    private Double price;

    private String description;

    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 Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                '}';
    }

    public Product(String id, String name, Double price, String description) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
    }
}

商品信息类

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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/index",loadOnStartup = 1)//让init()在应用启动时被调用
public class IndexServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        //准备一些商品数据 用这种方式来模拟从数据里面获取数据
        // alt + 鼠标左键  纵向选择
        Product product1 = new Product("1", "iphone12", 5600.0, "new version of iphone");
        Product product2 = new Product("2", "Mi11", 5200.0, "Mi flagship version");
        Product product3 = new Product("3", "Huawei Mate40", 4500.0, "Huawei");
        Product product4 = new Product("4", "One Plus 9", 6000.0, "One Plus");
        List<Product> products = new ArrayList<>();
        products.add(product1);
        products.add(product2);
        products.add(product3);
        products.add(product4);
        //如何将products和其他servlet进行共享 context域
        getServletContext().setAttribute("products", products);
     }

    
//  在首页显示商品名字
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        List<Product> products = (List<Product>) getServletContext().getAttribute("products");
        for (Product product : products) {
            //在商品名字上加上超链接,可以点进去看商品详情
            response.getWriter().println("<div><a href='"+ request.getContextPath() + "/detail?id=" + product.getId() + "'>" + product.getName() + "</a></div>");
        }
        response.getWriter().println("您的历史访问足迹为:");
        History.showView(request, response);
    }
}

首页显示

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 java.io.IOException;
import java.util.List;

@WebServlet("/detail")
public class DetailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //首先需要拿到id的值,商品的其他信息拿到(和context域里面的数据进行比对)
        // requestURI - contextPath  = servletPath  /detail
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        //把请求给历史记录,更新历史记录
        History.updateView(request);

        List<Product> products = (List<Product>) getServletContext().getAttribute("products");
        for (Product product : products) {
            if(id.equals(product.getId())){
                response.getWriter().println(product);
            }
        }

        //实现3个超链接
        String index = response.encodeURL(request.getContextPath() + "/index");
        String addCart = response.encodeURL(request.getContextPath() + "/addCart?id=" + id );
        String viewCart = response.encodeURL(request.getContextPath() + "/viewCart");

        response.getWriter().println("<a href='" + index + "'>返回首页</a>");
        response.getWriter().println("<a href='" + addCart + "'>加入购物车</a>");
        response.getWriter().println("<a href='" + viewCart + "'>查看购物车</a>");

    }
}

商品详情

 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class History {

    private static final int CAPACITY = 3;//历史记录最多显示3条

    //更新历史记录
    public static void updateView(HttpServletRequest request) {
        String id = request.getParameter("id");//获得当前访问的商品id
        HttpSession session = request.getSession();//每个用户有一个历史记录集合
        //历史足迹和用户是相关的,所以应该使用session
        //request:非常小; 三个以上页面使用不可能使用转发
        //context:只要涉及到和用户相关的,那么肯定不能用
        LinkedList<String> history = (LinkedList<String>) session.getAttribute("history");
        if(history == null){
            //因为历史记录要经常做增删操作,用链表更合适
            history = new LinkedList<>();
            session.setAttribute("history", history);
        }
        //把id存入到list中 1.当前id已经在链表内  2.当前id不在链表内  哪个情况需要考虑会不会超出history的容量
        if(history.contains(id)){
            history.remove(id);
        }else {
            if(history.size() == CAPACITY){
                history.removeLast();
            }
        }
        history.addFirst(id);
    }

    //显示历史记录
    //就是从history出取出id,然后通过id拿到id对应的其他信息
    public static void showView(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LinkedList<String> history = (LinkedList) request.getSession().getAttribute("history");
        if(history != null){
            List<Product> products = (List<Product>) request.getServletContext().getAttribute("products");
            for (String id : history) {
                for (Product product : products) {
                    if(id.equals(product.getId())){
                        String detail = response.encodeURL(request.getContextPath() + "/detail?id=" + product.getId());
                        response.getWriter().println("<div><a href='" + detail + "'>" + product.getName() + "</a></div>");
                    }
                }
            }
        }
    }
}

历史记录处理逻辑

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaEE 购物车实现可以分为以下几个步骤: 1. 创建商品实体类 首先,我们需要创建一个商品实体类来表示商品的基本信息,例如商品名称、价格、描述等等。 ```java public class Product { private int id; private String name; private String description; private double price; // 构造方法、getters、setters } ``` 2. 创建购物车实体类 接下来,我们需要创建一个购物车实体类来表示购物车的基本信息,例如购物车中的商品列表、总价等等。 ```java public class ShoppingCart { private List<Product> productList; private double totalPrice; // 构造方法、getters、setters } ``` 3. 创建购物车展示页面 我们可以使用 JSP 或者 Thymeleaf 等模板引擎来创建购物车展示页面,并在页面中展示购物车中的商品列表以及总价信息。 ```html <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Shopping Cart</title> </head> <body> <h1>Shopping Cart</h1> <table> <thead> <tr> <th>Product Name</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> <tr th:each="product : ${shoppingCart.productList}"> <td th:text="${product.name}"></td> <td th:text="${product.description}"></td> <td th:text="${product.price}"></td> </tr> </tbody> </table> <p>Total Price: <span th:text="${shoppingCart.totalPrice}"></span></p> </body> </html> ``` 4. 实现购物车功能 最后,我们需要实现购物车的基本功能,例如添加商品到购物车、从购物车中删除商品、计算购物车总价等等。 ```java public class ShoppingCartService { public void addProduct(Product product, ShoppingCart shoppingCart) { List<Product> productList = shoppingCart.getProductList(); productList.add(product); shoppingCart.setProductList(productList); shoppingCart.setTotalPrice(shoppingCart.getTotalPrice() + product.getPrice()); } public void removeProduct(Product product, ShoppingCart shoppingCart) { List<Product> productList = shoppingCart.getProductList(); productList.remove(product); shoppingCart.setProductList(productList); shoppingCart.setTotalPrice(shoppingCart.getTotalPrice() - product.getPrice()); } } ``` 以上就是 JavaEE 购物车的基本实现步骤,可以根据需求进行扩展和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值