• 购物车系列教材 (四)- 模块


    从开发者的角度来看,购买行为 就是创建一条一条的订单项 
    而显示购物车,也就是把这些订单项显示在页面上。 

    在这个阶段,订单项都会保存在session中,直到最后生成订单的时候,才会把这些订单项保存在数据库中。

    步骤1:SQL
    步骤2:OrderItem
    步骤3:ProductDAO
    步骤4:购买商品
    步骤5:显示购物车内容
    步骤6:购买相同商品
    步骤7:配置web.xml
    步骤8:测试
    步骤9:练习-删除订单项
    步骤10:答案-删除订单项
    步骤11:练习-加入购物车
    步骤12:答案-加入购物车

    步骤 1 : SQL

    暂时不需要为OrderItem创建表,因为在这个环节OrderItem还是保存在Session中的

    步骤 2 : OrderItem

    OrderItem使用属性Product类型的product,而非int类型的pid,因为在后续显示购物车的时候,可以很简单的通过el表达式就显示商品名称和价格了

    ${oi.product.name}

    package bean;

    public class OrderItem {

        private int id;

        private Product product;

        private int num;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public Product getProduct() {

            return product;

        }

        public void setProduct(Product product) {

            this.product = product;

        }

        public int getNum() {

            return num;

        }

        public void setNum(int num) {

            this.num = num;

        }

    }

    步骤 3 : ProductDAO

    因为购买的时候,提交到服务器的是pid, 而OrderItem类的product属性是一个Product类型

    所以ProductDAO需要根据id获取Product对象

    package dao;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.util.ArrayList;

    import java.util.List;

    import bean.Product;

    public class ProductDAO {

        public static void main(String[] args) {

            System.out.println(new ProductDAO().getProduct(1).getName());

        }

        public Product getProduct(int id) {

            Product result = null;

            try {

                Class.forName("com.mysql.jdbc.Driver");

                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cart?characterEncoding=UTF-8",

                        "root""admin");

                String sql = "select * from product where id = ?";

                PreparedStatement ps = c.prepareStatement(sql);

                ps.setInt(1, id);

                ResultSet rs = ps.executeQuery();

                if (rs.next()) {

                    result = new Product();

                    result.setId(id);

                    String name = rs.getString(2);

                    float price = rs.getFloat(3);

                    result.setName(name);

                    result.setPrice(price);

                }

                ps.close();

                c.close();

            catch (ClassNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            catch (SQLException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            return result;

        }

        public List<Product> ListProduct() {

            List<Product> products = new ArrayList<Product>();

            try {

                Class.forName("com.mysql.jdbc.Driver");

                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cart?characterEncoding=UTF-8",

                        "root""admin");

                String sql = "select * from product order by id desc";

                PreparedStatement ps = c.prepareStatement(sql);

                ResultSet rs = ps.executeQuery();

                while (rs.next()) {

                    Product product = new Product();

                    int id = rs.getInt(1);

                    String name = rs.getString(2);

                    float price = rs.getFloat(3);

                    product.setId(id);

                    product.setName(name);

                    product.setPrice(price);

                    products.add(product);

                }

                ps.close();

                c.close();

            catch (ClassNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            catch (SQLException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            return products;

        }

    }

    步骤 4 : 购买商品

    购买行为本身就是创建一个OrderItem对象
    在负责购买商品的OrderItemAddServlet 中,进行如下流程
    1. 获取购买数量
    2. 获取购买商品的id
    3. 根据id获取商品对象
    4. 创建一个新的OrderItem对象
    5. 从session中取出一个List , 这个List里面存放陆续购买的商品。
     如果是第一次从session中获取该List,那么它会是空的,需要创建一个ArrayList
    6. 把新创建的OrderItem对象放入该List 中
    7. 跳转到显示购物车的listOrderItem

    package servlet;

    import java.io.IOException;

    import java.util.ArrayList;

    import java.util.List;

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import bean.OrderItem;

    import bean.Product;

    import dao.ProductDAO;

    public class OrderItemAddServlet extends HttpServlet {

        protected void service(HttpServletRequest request, HttpServletResponse response)

                throws ServletException, IOException {

            int num = Integer.parseInt(request.getParameter("num"));

            int pid = Integer.parseInt(request.getParameter("pid"));

            Product p = new ProductDAO().getProduct(pid);

            OrderItem oi = new OrderItem();

            oi.setNum(num);

            oi.setProduct(p);

            List<OrderItem> ois = (List<OrderItem>) request.getSession().getAttribute("ois");

            if (null == ois) {

                ois = new ArrayList<OrderItem>();

                request.getSession().setAttribute("ois", ois);

            }

             

            ois.add(oi);

            response.sendRedirect("/listOrderItem");

        }

    }

    步骤 5 : 显示购物车内容

    显示购物车的OrderItemListServlet 其实什么也没做,因为数据已经在session准备好了,直接服务端跳转到listOrderItem.jsp

    在listOrderItem.jsp中,从session中遍历出所有的OrderItem。 因为保存在OrderItem 上的是一个Product对象,所以很容易就可以通过EL表达式遍历出商品的名称和价格。

    ${oi.product.name}

    ${oi.product.price}

    显示购物车内容

    package servlet;

    import java.io.IOException;

    import java.util.List;

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import bean.Product;

    import dao.ProductDAO;

    public class OrderItemListServlet extends HttpServlet

    {

        protected void service(HttpServletRequest request, HttpServletResponse response)

                throws ServletException, IOException {

            request.getRequestDispatcher("listOrderItem.jsp").forward(request, response);

        }

    }

    <%@ page language="java" contentType="text/html; charset=UTF-8"

        pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <h1 align="center" >购物车</h1>

    <table align='center' border='1' cellspacing='0'>

        <tr>

            <td>商品名称</td>

            <td>单价</td>

            <td>数量</td>

            <td>小计</td>

        </tr>

        <c:forEach items="${ois}" var="oi" varStatus="st">

            <tr>

                <td>${oi.product.name}</td>

                <td>${oi.product.price}</td>

                <td>${oi.num}</td>

                <td>${oi.product.price*oi.num}</td>

            </tr>

        </c:forEach>

    </table>

    步骤 6 : 购买相同商品

    遍历session中所有的OrderItem

    如果找到对应的product.id一样的条目,就调整其数量
    如果没有找到,就新增加一条

    package servlet;

    import java.io.IOException;

    import java.util.ArrayList;

    import java.util.List;

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import bean.OrderItem;

    import bean.Product;

    import dao.ProductDAO;

    public class OrderItemAddServlet extends HttpServlet {

        protected void service(HttpServletRequest request, HttpServletResponse response)

                throws ServletException, IOException {

            int num = Integer.parseInt(request.getParameter("num"));

            int pid = Integer.parseInt(request.getParameter("pid"));

            Product p = new ProductDAO().getProduct(pid);

            OrderItem oi = new OrderItem();

            oi.setNum(num);

            oi.setProduct(p);

            List<OrderItem> ois = (List<OrderItem>) request.getSession().getAttribute("ois");

            if (null == ois) {

                ois = new ArrayList<OrderItem>();

                request.getSession().setAttribute("ois", ois);

            }

            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);

            response.sendRedirect("/listOrderItem");

        }

    }

    步骤 7 : 配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <web-app>

        <servlet>

            <servlet-name>ProductListServlet</servlet-name>

            <servlet-class>servlet.ProductListServlet</servlet-class>

        </servlet>

        <servlet-mapping>

            <servlet-name>ProductListServlet</servlet-name>

            <url-pattern>/listProduct</url-pattern>

        </servlet-mapping>

        <servlet>

            <servlet-name>UserLoginServlet</servlet-name>

            <servlet-class>servlet.UserLoginServlet</servlet-class>

        </servlet>

        <servlet-mapping>

            <servlet-name>UserLoginServlet</servlet-name>

            <url-pattern>/login</url-pattern>

        </servlet-mapping>

        <servlet>

            <servlet-name>OrderItemAddServlet</servlet-name>

            <servlet-class>servlet.OrderItemAddServlet</servlet-class>

        </servlet>

        <servlet-mapping>

            <servlet-name>OrderItemAddServlet</servlet-name>

            <url-pattern>/addOrderItem</url-pattern>

        </servlet-mapping>

         

        <servlet>

            <servlet-name>OrderItemListServlet</servlet-name>

            <servlet-class>servlet.OrderItemListServlet</servlet-class>

        </servlet>

        <servlet-mapping>

            <servlet-name>OrderItemListServlet</servlet-name>

            <url-pattern>/listOrderItem</url-pattern>

        </servlet-mapping>

    </web-app>

    步骤 8 : 测试

    从登陆页面开始,登陆后到产品显示页面,然后修改购买数量,最后点击购买

    http://127.0.0.1/login.jsp


    更多内容,点击了解: https://how2j.cn/k/cart/cart-cart/598.html

  • 相关阅读:
    ubuntu下ssh服务相关操作
    搜索引擎的基础-倒排索引
    mysql重置密码
    mysql 服务器配置
    Activiti如何替换已部署流程图
    循环select查询结果集
    存储过程范例,有输入输出参数,带回滚
    sql server中字符串无法替换空格的问题
    Myeclipse实用快捷键总结
    Linux中添加用户与删除用户
  • 原文地址:https://www.cnblogs.com/Lanht/p/12789430.html
Copyright © 2020-2023  润新知