欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能

程序员文章站 2022-03-07 11:29:12
基本功能描述本项目实现的是一个可视化的购物车系统,其主要功能如下。用户进入登录页面进行登录,登陆成功则跳转到购物车主页面。由于登录页面在前一篇博客中已说明,本篇博客不再赘述,有需要者可以点击此链接查看。通过连接数据库显示图书信息,用户可以选择要加入购物车的物品数量,所加入的物品信息在我的购物车中即可查看。我的购物车中对所加入购物车的商品进行查看,同时可进行数量修改和删除,清空购物车等功能。图书管理页面是对数据库中的商品信息的展示,可以添加图书,也可以对价格,售卖情况等信息进行修改添加删除等,实...

基本功能描述

本项目实现的是一个可视化的购物车系统,其主要功能如下。

  • 用户进入登录页面进行登录,登陆成功则跳转到购物车主页面。由于登录页面在前一篇博客中已说明,本篇博客不再赘述,有需要者可以在此链接中查看:https://blog.csdn.net/qq_43505820/article/details/109562912。
  • 通过连接数据库显示图书信息,用户可以选择要加入购物车的物品数量,所加入的物品信息在我的购物车中即可查看。
  • 我的购物车中对所加入购物车的商品进行查看,同时可进行数量修改和删除,清空购物车等功能。
  • 图书管理页面是对数据库中的商品信息的展示,可以添加图书,也可以对价格,售卖情况等信息进行修改添加删除等,实现基本的增删改查操作。
  • 购物车和图书管理都实现了分页功能(数据过多无法在一个页面显示,可使用分页功能使其可视化更强。)
    (备注:读者在实现功能的时候可以将其细化,比如用户只能进入购物车页面无法查看后台的图书数据,只有管理员才能进入图书管理系统)

页面展示

购物车主页面
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
我的购物车页面展示
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
图书管理页面
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能

购物车数据库信息

本项目使用的是mysql:建表如下:

CREATE TABLE `shopbook` (                                                                                                                                                                                                                                                                                                                                               
            `id` int(11) NOT NULL AUTO_INCREMENT,                                                                                                                                                                                                                                                                                                                                 
            `name1` varchar(100) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                    
            `author` varchar(100) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                   
            `price` decimal(11,2) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                   
            `sales` int(11) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                         
            `stock` int(11) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                         
            `img_path` varchar(200) DEFAULT NULL,                                                                                                                                                                                                                                                                                                                                 
            PRIMARY KEY (`id`)                                                                                                                                                                                                                                                                                                                                                    
          ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8   

具体数据请自己进行添加。

代码路径展示

史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能

代码实现

bean基本属性的配置

Books属性:

package bean;

import java.math.BigDecimal;

public class Books {
    private Integer id;
    private String name1;
    private String author;
    private BigDecimal price;
    private Integer sales;//出售量
    private Integer stock;//库存量
    //默认图片路径
    private String imgPath="img/6f99aa07366c5fb5.jpg";
    public Books(){}
    public Books(Integer id, String name, String author, BigDecimal price, Integer sales, Integer stock, String imgPath) {
        this.id = id;
        this.name1 = name;
        this.author = author;
        this.price = price;
        this.sales = sales;
        this.stock = stock;
        if(imgPath!=null&&!"".equals(imgPath)) {
            this.imgPath = imgPath;
        }
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name1;
    }

    public void setName(String name) {
        this.name1 = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public BigDecimal getPrice() {
        return price;
    }

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

    public Integer getSales() {
        return sales;
    }

    public void setSales(Integer sales) {
        this.sales = sales;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public String getImgPath() {
        return imgPath;
    }

    public void setImgPath(String imgPath) {
        if(imgPath!=null&&!"".equals(imgPath)) {
            this.imgPath = imgPath;
        }
    }

    @Override
    public String toString() {
        return "Books{" +
                "id=" + id +
                ", name='" + name1 + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", sales=" + sales +
                ", stock=" + stock +
                ", imgPath='" + imgPath + '\'' +
                '}';
    }
}

Cart:

package bean;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

public class Cart{
   // private Integer totalCount;
   // private BigDecimal totalPrice;
    private Map<Integer,CartItem> items=new LinkedHashMap<>();
    public Cart(){}
    @Override
    public String toString() {
        return "Cart{" +
                "totalCount=" + getTotalCount() +
                ", totalPrice=" + getTotalPrice() +
                ", items=" + items +
                '}';
    }
    //通过map进行遍历
    public Integer getTotalCount() {
        Integer totalCount=0;
        for(Map.Entry<Integer,CartItem> entry:items.entrySet()){
            totalCount+=entry.getValue().getCount();
        }
        return totalCount;
    }

    public BigDecimal getTotalPrice() {
        BigDecimal totalPrice=new BigDecimal(0);
        for(Map.Entry<Integer,CartItem> entry:items.entrySet()){
            totalPrice=totalPrice.add(entry.getValue().getTotalPrice());
        }
        return totalPrice;
    }

    public Map<Integer,CartItem> getItems() {
        return items;
    }

    public void setItems(Map<Integer,CartItem> items) {
        this.items = items;
    }
    //添加商品
    public void addItem(CartItem cartItem){
        //获取到cartItem的ID 对他的属性进行添加
        CartItem item = items.get(cartItem.getId());
        items.put(cartItem.getId(),cartItem);
    }
    public void deleteItem(Integer id){
      items.remove(id);
    }
    //清空购物车
    public void clear(){
     items.clear();
    }
    //修改商品数量
    public void updateCount(Integer id,Integer count){
     //先查看购物车中是否有该商品,有则修改商品数量
        CartItem cartItem = items.get(id);
        if(cartItem!=null){
            cartItem.setCount(count);
            cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));
        }
    }

}

CartItem:

package bean;

import java.math.BigDecimal;

public class CartItem {
    private Integer id;
    private String name;
    private Integer count;
    private BigDecimal price;
    private BigDecimal totalPrice;
   public CartItem(){}

    public CartItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice) {
        this.id = id;
        this.name = name;
        this.count = count;
        this.price = price;
        this.totalPrice = totalPrice;
    }

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public BigDecimal getPrice() {
        return price;
    }

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

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }
}

Page:

package bean;

import java.util.List;

/**
 * 
 * @createTime 2020/11/26 9:17
 * @description
 */

public class Page<T> {
    //每页显示数量
    public static final Integer Page_Size=4;
    //当前页码
    private Integer pageNo;
    //总页码
    private Integer pageTotal;
    private Integer pageSize=Page_Size;
    //总记录数
    private Integer pageTotalCount;
    //当前页数据
    private List<T>  item;
    @Override
    public String toString() {
        return "Page{" +
                "pageNo=" + pageNo +
                ", pageTotal=" + pageTotal +
                ", pageSize=" + pageSize +
                ", pageTotalCount=" + pageTotalCount +
                ", item=" + item +
                '}';
    }
    public static Integer getPage_Size() {
        return Page_Size;
    }
    public Integer getPageNo() {
        return pageNo;
    }
    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }
    public Integer getPageTotal() {
        return pageTotal;
    }
    public void setPageTotal(Integer pageTotal) {
        this.pageTotal = pageTotal;
    }
    public Integer getPageSize() {
        return pageSize;
    }
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    public Integer getPageTotalCount() {
        return pageTotalCount;
    }
    public void setPageTotalCount(Integer pageTotalCount) {
        this.pageTotalCount = pageTotalCount;
    }
    public List<T> getItem() {
        return item;
    }
    public void setItem(List<T> item) {
        this.item = item;
    }
}

User:

package bean;
public class User {
    private String name;
    private String pd;
    public User(){}
    public String getPd() {
        return pd;
    }
    public void setPd(String pd) {
        this.pd = pd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

dao路径下对数据库进行的处理

BookDao:

package dao.impl;
import bean.Books;
import java.util.List;
/**
 * @createTime 2020/11/24 14:51
 * @description
 */

public interface BookDao {
    //实现增删改查
    public int addBook(Books book);
    public int deleteBookById(Integer id);
    public int updateBook(Books book);
    public Books queryBookById(Integer id);
    public List<Books> queryBooks();
    public int queryForPageTotalCount();
    public List<Books> queryForPageItems(Integer begin, Integer pageSize);
}

BookDaoImpl

package dao.impl;

import bean.Books;
import bean.Page;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;


//访问数据库  对数据库进行增删改查操作
public class BookDaoImpl implements BookDao {
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    Connection con = null;
    //向数据库中添加书
    @Override
    public int addBook(Books book) {
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "insert into shopbook(name1,author,price,sales,stock,img_path) values (?,?,?,?,?,?) ";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, book.getName());
            preparedStatement.setString(2, book.getAuthor());
            preparedStatement.setBigDecimal(3, book.getPrice());
            preparedStatement.setInt(4, book.getSales());
            preparedStatement.setInt(5, book.getStock());
            preparedStatement.setString(6, book.getImgPath());
            preparedStatement.execute();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return 1;
    }

    //根据提供书的ID将数据删除
    @Override
    public int deleteBookById(Integer id) {
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "delete from shopbook where id=?";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setInt(1, id);
            preparedStatement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return 1;
    }
//更新书信息
    @Override
    public int updateBook(Books book) {
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "update shopbook set name1=?,author=?,price=?,sales=?,stock=?,img_path=? where id=?";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, book.getName());
            preparedStatement.setString(2, book.getAuthor());
            preparedStatement.setBigDecimal(3, book.getPrice());
            preparedStatement.setInt(4, book.getSales());
            preparedStatement.setInt(5, book.getStock());
            preparedStatement.setString(6, book.getImgPath());
            preparedStatement.setInt(7, book.getId());
            preparedStatement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }
//通过ID查询到书的信息
    @Override
    public Books queryBookById(Integer id) {
        Books books = new Books();
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "select id,name1,author,price,sales,stock,img_path imgPath from shopbook where id=? ";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                books.setId(rs.getInt("id"));
                books.setName(rs.getString("name1"));
                books.setAuthor(rs.getString("author"));
                books.setPrice(rs.getBigDecimal("price"));
                books.setSales(rs.getInt("sales"));
                books.setStock(rs.getInt("stock"));
                books.setImgPath(rs.getString("imgPath"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return books;
    }
//查询所有图书
    @Override
    public List<Books> queryBooks() {
        List<Books> books = new LinkedList<>();
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "select id,name1,author,price,sales,stock,img_path imgPath from shopbook";
            preparedStatement = con.prepareStatement(sql);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                Books books1 = new Books();
                books1.setId(rs.getInt("id"));
                books1.setName(rs.getString("name1"));
                books1.setAuthor(rs.getString("author"));
                books1.setPrice(rs.getBigDecimal("price"));
                books1.setSales(rs.getInt("sales"));
                books1.setStock(rs.getInt("stock"));
                books1.setImgPath(rs.getString("imgPath"));
                books.add(books1);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return books;
    }
//获取所有信息的个数
    @Override
    public int queryForPageTotalCount() {
        Statement statement=null;
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "select * from shopbook";
            statement=con.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            rs.last();
            return rs.getRow();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }
//获取从指定ID和count获取该部分的所有数据信息
    @Override
    public List<Books> queryForPageItems(Integer begin, Integer pageSize) {
        List<Books> books = new LinkedList<>();
        //启动mysql驱动器
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
            String sql = "select id,name1,author,price,sales,stock,img_path imgPath from shopbook limit ?,?";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setInt(1,begin);
            preparedStatement.setInt(2,pageSize);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                Books books1 = new Books();
                books1.setId(rs.getInt("id"));
                books1.setName(rs.getString("name1"));
                books1.setAuthor(rs.getString("author"));
                books1.setPrice(rs.getBigDecimal("price"));
                books1.setSales(rs.getInt("sales"));
                books1.setStock(rs.getInt("stock"));
                books1.setImgPath(rs.getString("imgPath"));
                books.add(books1);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return books;
    }
}

首页代码

注意首页面代码(使用idea在没有设置默认路径的时候默认启动的是index.jsp页面,可以在此处写入,防止代码过多忘记从哪个页面开始启动):
index.jsp:

<%@ page contentType="text/html;charset=gb2312" pageEncoding="gb2312" language="java" import="bean.*"
%>
<html>
<head>
    <title>welcome</title>
</head>
<body>
<a href="http://localhost:8080/BookServlet?action=firstPage">进入购物页面</a>
</body>
</html>

BookServlet逻辑处理

BookServlet中的firstPage对商品信息显示进行处理,此类提供的其他方法后面会用到。

package servlet;

import bean.Books;
import bean.Page;
import dao.impl.BookDaoImpl;

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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
     BookDaoImpl bookDao=new BookDaoImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doGet(request,response);
    }

    //获取路径中action后要进行的操作
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //中文乱码解决方法
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action=request.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    //实现数据的添加操作
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   //Book类 book的基本属性:包括 ID name author price sales stock imgPath
    Books books=new Books();
     books.setName(request.getParameter("name"));
     books.setAuthor(request.getParameter("author"));
     String price = request.getParameter("price");
         BigDecimal bigDecimal = new BigDecimal(price);
         books.setPrice(bigDecimal);
     books.setSales(Integer.parseInt(request.getParameter("sales")));
     books.setStock(Integer.parseInt(request.getParameter("stock")));
     //访问数据库
     bookDao.addBook(books);
     //跳转到显示数据的页面
     response.sendRedirect(request.getContextPath()+"/BookServlet?action=page");
    }
    //对信息删除
    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        bookDao.deleteBookById(Integer.parseInt(id));
        response.sendRedirect(request.getContextPath()+"/BookServlet?action=page");
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        String id=(String)session.getAttribute("id");
        Books books=new Books();
        books.setId(Integer.parseInt(id));
        books.setName(request.getParameter("name"));
        books.setAuthor(request.getParameter("author"));
        String price = request.getParameter("price");
        BigDecimal bigDecimal = new BigDecimal(price);
        books.setPrice(bigDecimal);
        books.setSales(Integer.parseInt(request.getParameter("sales")));
        books.setStock(Integer.parseInt(request.getParameter("stock")));
        bookDao.updateBook(books);
        response.sendRedirect(request.getContextPath()+"/BookServlet?action=page");
    }
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //查询全部图书
        List<Books> books = bookDao.queryBooks();
        HttpSession session=request.getSession();
        //把图书存放在request域中
        session.setAttribute("books",books);
        //请求转发到bookmanage.jsp页面
        request.getRequestDispatcher("jspdemo/bookManage.jsp").forward(request,response);
    }
    //根据ID查找book  可以对数据进行修改操作
    protected void getBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Books book = bookDao.queryBookById(Integer.parseInt(id));
        request.setAttribute("book",book);
        request.getRequestDispatcher("jspdemo/bookEdit.jsp").forward(request,response);
    }
    //分页处理
    //一个page 是进入到后台管理的图书分页 另一个是进入到主页面购物车
    // 两个实现方式相同  跳转路径不同
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取参数  pageno pagesize
        String pageNo = request.getParameter("pageNo");
        int pageNo1=0;
        if(pageNo!=null){
            pageNo1 = Integer.parseInt(pageNo);
        }
        else {
            pageNo1=1;
        }
        String pageSize = request.getParameter("pageSize");
        int pageSize1=0;
        if(pageSize==null){
            pageSize1=Page.Page_Size;
        }
        else {
            pageSize1=Integer.parseInt(pageSize);
        }
        //调用bookdao.page  保存page对象到request  已知当前页和每页数量 获取到当前page的所有信息
        Page<Books> page=page1(pageNo1,pageSize1);
        // 请求转发到显示页面
        request.setAttribute("page",page);
        request.getRequestDispatcher("jspdemo/bookManage.jsp").forward(request,response);
    }

    //补充page属性的信息
    public Page<Books> page1(int pageNo, int PageSize) {
        Page<Books> page=new Page<>();
        //赋值
        page.setPageNo(pageNo);
        page.setPageSize(PageSize);
        //总记录数  访问数据库 记录总共商品数量
        Integer pageTotalCount=bookDao.queryForPageTotalCount();
        page.setPageTotalCount(pageTotalCount);
        //总页码
        Integer pageTotal=pageTotalCount/PageSize;
        if(pageTotalCount%PageSize>0){
            pageTotal++;
        }
        page.setPageTotal(pageTotal);
        //求当前的信息  当前页面的第一个数据的号
        //eg:一个页面显示四条数据  如果是第一个页面的话 显示的信息为0-3 共四条数据 后面类似
        int begin=(pageNo-1)*PageSize;
       //访问数据库
        List<Books> items=bookDao.queryForPageItems(begin,PageSize);
       //求当前页数据
        page.setItem(items);
        return page;
    }
    //分页处理   进入初始页面
    protected void firstPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数  pageno pagesize
        String pageNo = request.getParameter("pageNo");
        int pageNo1=0;
        if(pageNo!=null){
            pageNo1 = Integer.parseInt(pageNo);
        }
        else {
            pageNo1=1;
        }
        String pageSize = request.getParameter("pageSize");
        int pageSize1=0;
        if(pageSize==null){
            pageSize1=Page.Page_Size;
        }
        else {
            pageSize1=Integer.parseInt(pageSize);
        }
        //调用bookdao.page  保存page对象到request
        Page<Books> page=page1(pageNo1,pageSize1);
        // 请求转发到显示页面
        request.setAttribute("page",page);
        request.getRequestDispatcher("index1.jsp").forward(request,response);
    }
}

主页面展示页面

index1.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>书城购物系统</title>
</head>
<body>
<h1 align=center><font color="#8a2be2" > 欢迎来到书城购物系统,祝您生活愉快</font></h1><hr>
<h4 align=right><a href="/BookServlet?action=page">图书管理</a>&nbsp;&nbsp;&nbsp;<a href="jspdemo/cart.jsp">我的购物车</a> </h4>
<hr>
<style>
    li {float:left;list-style:none;}
</style>
<script type="text/javascript">
    function show() {
        alert("-_- 添加成功 -_-");
        shopping.submit();
    }
</script>
<c:forEach items="${requestScope.page.item}" var="book">
<ul>
    <li>
        <form name="shopping" action="/AddCartServlet" method="post">
        <img  src="${book.imgPath}"/><br>
        书名:${book.name}<br>作者:${book.author}<br>
        价格:${book.price}<br>销量:${book.sales}<br>库存:${book.stock}<br>
         <input type="hidden" name="id" value="${book.id}"><br>
            选择数量: <input type="text" name="count" size="3">
        <input type="submit" value="加入购物车" onclick="show()">
       </form>
    </li>
</ul>
</c:forEach>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<%--添加分页条--%>
<div id="page_nav">
    <c:if test="${requestScope.page.pageNo>1}">
        <a href="/BookServlet?action=firstPage&pageNo=1">首页</a>
        <a href="/BookServlet?action=firstPage&pageNo=${requestScope.page.pageNo-1}">上一页</a>
    </c:if>
    <c:forEach begin="1" end="${requestScope.page.pageTotal}" var="i">
        <a href="/BookServlet?action=firstPage&pageNo=${i}">${i}</a>
    </c:forEach>
    <c:if test="${requestScope.page.pageNo < requestScope.page.pageTotal}">
        <a href="/BookServlet?action=firstPage&pageNo=${requestScope.page.pageNo+1}">下一页</a>
        <a href="/BookServlet?action=firstPage&pageNo=${requestScope.page.pageTotal}">末页</a>
    </c:if>
    <form action="/BookSearchServlet1">
        共${requestScope.page.pageTotal}, ${requestScope.page.pageTotalCount}条记录
        跳转到<input value="4" type="text" name="p" ><input type="hidden" name="pageTotal"value="${requestScope.page.pageTotal}">
        <input  type="submit" value="确定">
    </form>
</div>
</body>
</html>

史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能

文本框输入页面数跳转到某个页面:
BookSearchServlet1.java

package servlet;

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;

@WebServlet("/BookSearchServlet1")
public class BookSearchServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String p = request.getParameter("p");
        int page = Integer.parseInt(p);
        String pageTotal = request.getParameter("pageTotal");
        int total = Integer.parseInt(pageTotal);
        if (page <= 1) {
            response.sendRedirect(request.getContextPath() + "/BookServlet?action=firstPage&pageNo=1");
        } else if (page >= total) {
            response.sendRedirect(request.getContextPath() + "/BookServlet?action=firstPage&pageNo=" + total);
        } else {
            response.sendRedirect(request.getContextPath() + "/BookServlet?action=firstPage&pageNo=" + p);
        }
    }
}

加入购物车后点击我的购物车便可查看加入购物车的信息,同时可对购物车里面的数量进行修改:

cart.jsp购物车信息展示

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>我的购物车</title>
</head>
<body>
<c:if test="${empty sessionScope.cart.items}">
    亲亲,你的购物车目前是空的呢 <a href="http://localhost:8080/BookServlet?action=firstPage">点击此处返回购物页面</a>
</c:if>
<%--如果购物车不是空的则会显示以下内容--%>
<c:if test="${not empty sessionScope.cart.items}">
<table>
<tr>
    <td>商品名称</td>
    <td>数量</td>
    <td>单价</td>
    <td>金额</td>
    <td colspan="2">操作</td>
</tr>

<c:forEach items="${sessionScope.cart.items}" var="entry">
    <form action="/UpdateCartServlet">
    <tr>
    <td>${entry.value.name}&nbsp;&nbsp;</td>
    <td><input type="text"  style="width: 80px;" name="count" value="${entry.value.count}"></td>
    <td>${entry.value.price}&nbsp;&nbsp;</td>
    <td>${entry.value.totalPrice}&nbsp;&nbsp;</td>
        <!--隐秘传入ID  为更新操作服务 -->
        <input type="hidden" name="id" value="${entry.value.id}">
        <td><input type="submit" value="修改"></td>
        <td><a href="/CartServlet?action=delete&id=${entry.value.id}">删除</a></td>
    </tr>
    </form>
    </c:forEach>
</table>
    购物车*有 ${sessionScope.cart.totalCount}件商品&nbsp;&nbsp;总金额为${sessionScope.cart.totalPrice}<a href="/CartServlet?action=clear">清空购物车</a>&nbsp;&nbsp;
<a href="http://localhost:8080/BookServlet?action=firstPage">返回购物页面</a>&nbsp;&nbsp; 去结账
    </c:if>
</body>
</html>

史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能
在这里可以直接在文本框中对数量进行修改,点击修改便完成。
修改处理对应的代码:
UpdateCartServlet.java

package servlet;
import bean.Books;
import bean.Cart;
import bean.CartItem;
import dao.impl.BookDaoImpl;
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;
@WebServlet("/UpdateCartServlet")
public class UpdateCartServlet extends HttpServlet {
    BookDaoImpl bookDao=new BookDaoImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        update(request,response);
    }
    //修改购物车数量
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id1=request.getParameter("id");
        String count1=request.getParameter("count");
        int id=0,count=0;
        if(id1!=null){
            id=Integer.parseInt(id1);
        }
        if(count1!=null){
            count=Integer.parseInt(count1);
        }
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if(cart!=null){
            cart.updateCount(id,count);
        }
        //返回上个页面
        response.sendRedirect(request.getHeader("Referer"));
    }
}

对购物车的商品信息进行删除或者进行清空购物车,修改数量的操作时,调用CartServlet.java的代码

package servlet;
import bean.Books;
import bean.Cart;
import bean.CartItem;
import dao.impl.BookDaoImpl;

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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    BookDaoImpl bookDao=new BookDaoImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //中文乱码解决方法
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action=request.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
   //删除信息
    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       String id1=request.getParameter("id");
       int id=0;
       if(id1!=null){
           id=Integer.parseInt(id1);
       }
       Cart cart=(Cart)request.getSession().getAttribute("cart");
       if(cart!=null){
           cart.deleteItem(id);
           response.sendRedirect(request.getHeader("Referer"));
       }
   }
   //清空购物车
   protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       Cart cart = (Cart)request.getSession().getAttribute("cart");
       cart.clear();
       response.sendRedirect(request.getHeader("Referer"));
    }
    //修改购物车数量
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id1=request.getParameter("id");
        String count1=request.getParameter("count");
        System.out.println(count1);
        int id=0,count=0;
        if(id1!=null){
            id=Integer.parseInt(id1);
        }
        if(count1!=null){
            count=Integer.parseInt(count1);
        }
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if(cart!=null){
            cart.updateCount(id,count);
        }
        response.sendRedirect(request.getHeader("Referer"));
    }
}

图书后台信息管理

点击图书管理,程序会跳转到BookServlet调用其page方法,经过处理后跳转到bookManage.jsp界面,显示所有图书信息。

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2020/11/24
  Time: 21:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>图书管理</title>
</head>
<body>
<table>
    <tr>
        <td>名称</td>
        <td>作者</td>
        <td>价格</td>
        <td>销量</td>
        <td>库存</td>
        <td colspan="2">操作</td>
    </tr>
    <!--获取由bookservlet.page()传的值-->
    <c:forEach items="${requestScope.page.item}" var="book">
    <tr>
        <td>${book.name}</td>
        <td>${book.author}</td>
        <td>${book.price}</td>
        <td>${book.sales}</td>
        <td>${book.stock}</td>
        <td><a href="/BookServlet?action=getBook&id=${book.id}">操作</a></td>
        <td><a href="/BookServlet?action=delete&id=${book.id}">删除</a> </td>
    </tr>
    </c:forEach>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td><a href="jspdemo/bookEdit.jsp">添加图书</a></td>
    </tr>
</table>
<div id="page_nav">
    <c:if test="${requestScope.page.pageNo>1}">
        <a href="/BookServlet?action=page&pageNo=1">首页</a>
        <a href="/BookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">上一页</a>
    </c:if>
    <c:forEach begin="1" end="${requestScope.page.pageTotal}" var="i">
        <a href="/BookServlet?action=page&pageNo=${i}">${i}</a>
    </c:forEach>
<c:if test="${requestScope.page.pageNo < requestScope.page.pageTotal}">
    <a href="/BookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">下一页</a>
    <a href="/BookServlet?action=page&pageNo=${requestScope.page.pageTotal}">末页</a>
</c:if>
    <form action="/BookSearchServlet">
    共${requestScope.page.pageTotal}, ${requestScope.page.pageTotalCount}条记录
       跳转到<input value="4" type="text" name="p" ><input type="hidden" name="pageTotal"value="${requestScope.page.pageTotal}">
        <input  type="submit" value="确定">
   </form>
    <a href="http://localhost:8080/BookServlet?action=firstPage">返回购物页面</a>
</div>
</body>
</html>

史上功能最全Web购物车实现(基于jsp+java+servlet+dao)包括后台图书管理、实现数据库分页等功能

对后台信息可以进行添加删除修改,一般是管理员身份的可以对此进行操作。进行操作选项调用BookServlet的getBook方法,删除操作调用BookServlet的delete方法,添加调用bookEdit.jsp

bookEdit.jsp对后台图书进行添加操作

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2020/11/24
  Time: 22:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>信息编辑</title>
</head>
<body>
<!--如果路径后面没有ID则为添加商品信息,如果有ID则为修改商品信息-->
<form action="/BookServlet" method="post">
    <input type="hidden" name="action" value="${empty param.id? "add":"update"}">
    <%
    session.setAttribute("id", request.getParameter("id"));
    %>
    <table>
        <tr>
            <td>名称</td>
            <td>作者</td>
            <td>价格</td>
            <td>销量</td>
            <td>库存</td>
            <td colspan="2">操作</td>
        </tr>
        <tr>
            <td><input name="name" type="text" value="${requestScope.book.name}"></td>
            <td><input name="author" type="text" value="${requestScope.book.author}"></td>
            <td><input name="price" type="text" value="${requestScope.book.price}"></td>
            <td><input name="sales" type="text" value="${requestScope.book.sales}"></td>
            <td><input name="stock" type="text" value="${requestScope.book.stock}"></td>
            <td><input type="submit" value="添加"></td>
        </tr>
    </table>
</form>
</body>
</html>

该项目代码稍微长,但其思想原理却不是很复杂。主要是对数据库的基本操作和jsp的基本用法。
代码有难点的地方我都标了注释,仍有问题的欢迎打扰。

本文地址:https://blog.csdn.net/qq_43505820/article/details/110825677