Use Servlet and JSP to develop a simplified shopping cart

A few days ago, after reviewing the knowledge of Servlet and JSP, I wanted to summarize it, and then I wanted to develop a simplified version of the shopping cart. Although it is a simplified version, the logic of the shopping cart is basically the same as that of Tmall and Jingdong. Let's take a look at how this shopping cart is implemented.
Note: This article is based on the textbook of a certain big guy. I will explain the source at the end of the article.
Mainly develop the following points:

  • Class relationship
  • Product module
  • User module
  • Shopping Cart Module
  • Order module

First of all, we must first clarify some basic relationships. There are products , orders , users , and order items . The first three are all well understood. What is the fourth order item? To put it bluntly, an order item is a record, and several identical orders are placed in a session. So what is the relationship between them? There is a one-to-many relationship between products and order items, the relationship between order items and orders is many-to-one, and the relationship between orders and users is many-to-one. After introducing the relationship between classes and classes, we are about to develop.
First, we need to create a database and create a new product table, then insert four pieces of data for later use, Insert picture description here
and then create the corresponding entity class in the idea, the fields must correspond to the fields in the database, and then we need to create a product table The DAO is used to query data. Since it is a simplified version of the shopping cart, I only did query operations. Next, we need a servlet to call DAO and display the data on the browser. The code is as follows:

 @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Product> products = new ProductListDAO().list();
        req.setAttribute("Product",products);

        req.getRequestDispatcher("JSP/listProduct.jsp").forward(req, resp);
    }

The approximate meaning in JSP is that there is a table, and then each row is increased according to the passed array. The effect is shown in the figure:
Login effect
Effect of successful login
if the login fails, it will redirect to the login page. The login servlet code is as follows:

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        User user = new UserDAO().getUser(name, password);

        if (null != user.getName()){
            System.out.println("登录成功!");
            req.getSession().setAttribute("user",user);
            resp.sendRedirect("ProductListServlet");
        }else {
            System.out.println("登录失败!");
            resp.sendRedirect("index.jsp");
        }
    }

Then there is the user module. The user login implemented just now is the content of the user module. I will briefly describe the general implementation process. First, a user table is needed, then a corresponding entity class is needed, and then one is needed to query users. The DAO of the table content, let's call it UserListDAO, right? So we need a servlet, which is used to verify whether the input is correct or not is the above part of the code. If it is correct, pass the user's content to it, and login can be realized.
Then what needs to be done is the display module of the shopping cart. We might as well think carefully about how to realize which orders in the shopping cart are realized? It is not that the same order is placed in one order item, and then there will be many order items. You can buy the same product and buy one or more, but if you buy multiple, only one order item can be generated. If the same product Bought three, and then corresponded to three order items, this is incorrect. At this stage, the order items are stored in the session, and will be stored in the database only when the order is finally submitted.
Here we need to create a new order item class OrderItem, which contains the quantity and product information. Since the pid is submitted when the product is purchased, and the Product in the OrderItem, we need to find the price and name of the product according to the id . In fact, the purchase behavior itself is the process of creating an OrderItem, because every time you create a new order, you must create a new OiderItem object and then put the price name in, and finally add it to the collection. The collection is empty when it is first created Then put the first record into it, then jump to the display interface, and then add it directly after adding to the shopping cart.
It’s easier to display the shopping cart, almost all of them are done in the servlet, just display the data, and add a delete operation.
Shopping cart interface
I just said that the same order corresponds to an order item regardless of the quantity, and then we need to judge whether it is the same id in the servlet, and if so, just change the quantity.

 boolean found = false;
        for (OrderItem orderItem : ois) {
            if (orderItem.getProduct().getId() == oi.getProduct().getId()) {
                orderItem.setNum(orderItem.getNum() + oi.getNum());
                found = true;
                break;
            }
        }
 
        if (!found)
            ois.add(oi);

The general idea of ​​the delete operation is to pass this order item, that is, the id number of this product to the servlet, and then traverse the collection, compare, and if the corresponding order item is found, then remove this record. Jump to the shopping cart interface.

@Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = Integer.parseInt(req.getParameter("id"));
        List<OrderItem> ois ;
        ois = (List<OrderItem>) req.getSession().getAttribute("ois");
        for (OrderItem orderItem : ois) {
            if(orderItem.getProduct().getId()==id){
                ois.remove(orderItem);
                req.getSession().setAttribute("ois", ois);
                break;
            }
        }
        resp.sendRedirect("/listOrderItem");
    }

According to the logic of the shopping cart, all preparations have been made before placing an order. When we place an order on Taobao, we add to the shopping cart to determine the quantity and what to do next? Yes, the order is submitted and then the payment is made. After the order is submitted, the mission of the shopping cart is officially over. Then let's do the operation of emptying the shopping cart next!
Roughly finished the logic implementation of the shopping cart, let’s post a few pictures to see the effect. Let
Improved shopping cart interface
Order completion interface
’s talk about the logic after reading the effect. First, we need two tables, one is used to store user information, the other is used to store shopping The information table in the cart, the information in the shopping cart shows the number and price of the product name, and the corresponding user name, because every time an order is submitted is an order submitted by the same object, it cannot be two objects The same order is submitted, so after we know this logic, we need to create a new servlet to operate on it. We also need to create two DAOs. One is to store the user name and the other is to store the information in the shopping cart. , What is done in the servlet is to verify whether you have logged in (this is the logic of placing orders on major e-commerce platforms, if you do not log in, you must log in first). If it is not empty, first store the id of the user name in the database. With the id of the user, you can traverse the contents of the shopping cart, and then store the id of the user in each item, and then Store the entire order item in the database. When all the items in the shopping cart are stored, the shopping cart will be cleared, because the items in the shopping cart are a collection and no data table is involved, so we only need to call the collection The clear method can be cleared.
The servlet code to submit the order:

  @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User u = (User) req.getSession().getAttribute("user");
        if (null == u){
            resp.sendRedirect("JSP/index.jsp");
        }

        Order o = new Order();
        o.setUser(u);

        //将这个购物车的用户存入数据库
        new OrderDAO().insert(o);

        List<OrderItem> ois = (List<OrderItem>)req.getSession().getAttribute("ois");
        for (OrderItem oi:ois) {
            oi.setOrder(o);
            new OrderItemDAO().insert(oi);
        }

        //清空购物车
        ois.clear();

        resp.setContentType("text/html; charset=UTF-8");
        resp.sendRedirect("JSP/success.jsp");
    }

After being cleared, it means that the order is completed. It is ok to jump to the order completion interface. If you need to jump to the payment interface when you are actually shopping, since we are a simplified version here, we will do this step Omitted, as long as you know the general logic.
Well, the above is all the logic for developing a simplified shopping cart. Basically all e-commerce platforms have the same logic for developing a shopping cart, so it will be easier to develop a more comprehensive shopping cart with this logic. Keep working hard, Sao Nian~

References: https://how2j.cn/k/cart/cart-tutorials/595.html

Guess you like

Origin blog.csdn.net/weixin_44475741/article/details/112919316