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

JSP实现购物车功能(session+Map)

程序员文章站 2022-03-15 09:47:09
...

记录一下从上个项目中抽离出来的购物车功能:Jsp+Session+Map

先来看一下最后效果吧JSP实现购物车功能(session+Map)
我们先来整理一下购物车的开发思路:
1.确定将哪本书放入购物车,使用id来进行传值或者直接从Session取出
2.判断是否存在购物车,若存在则直接使用,不存在则创建
3.判断购物车是否存在当前存入的这本书,若存在,数量加1,否则存入该书,设置初始数量为1
4.将购物车存入Session,方便前台获取


下面开始放代码
JSP实现购物车功能(session+Map)
首先创建实体类:

package com.servlet;

/**
 * Book实体类
 */
public class Book {
    private Integer id;
    private String name;
    private  double price;

    public Book() {
    }

    public Book(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

    public void setId(int 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;
    }

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

数据库链接MySqlDao类:

package com.untils;

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;

/**
 * @title BaseDao
 * @author Bailu
 * @time 下午1:08:11
 *
 */
//数据库连接和关闭类
/**
 * 加载驱动
 * 创建连接对象
 * 准备sql语句
 * 创建执行对象
 * 执行并获取结果
 * 释放链接
 */
public class MysqlDB {
    public static Connection conn=null;
    public static PreparedStatement state= null;
    public static ResultSet result=null;


    public static Connection getConn() throws SQLException,ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true","root","root");//此处所用数据库为mysql8.0 其他版本的链接信息需要自行更改一下
        return conn;
    }
    /**
     *数据更新
     */
    public static int update(String sql,Object...obs) {
        int result = 0;
        try{
            conn = getConn();
            state = conn.prepareStatement(sql);
            for (int i = 0; i < obs.length; i++) {
                state.setObject(i+1, obs[i]);
            }
            result = state.executeUpdate();

        }catch(Exception e){
            e.printStackTrace();
        }
        return result;

    }
    /**
     *查询
     */
    public static ResultSet query(String sql,Object...obs) {
        try {
            conn=getConn();
            state=conn.prepareStatement(sql);
            for (int i = 0; i < obs.length; i++) {
                state.setObject(i+1, obs[i]);
            }
            result=state.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void closeObject(){
        try {
            if(result!=null){
                result.close();
            }
            if(result!=null){
                result.close();
            }
            if(result!=null){
                result.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

接下来写数据交互层:
首先定义好接口再实现

package com.dao;

import com.servlet.Book;

import java.util.List;

/**
 * BookDao接口
 */
public interface BookDao {
/**
*
**/ 
    public List<Book> select(String sql, Object[] arr);

    public Book getBook(Integer id);

}

接口实现:

package com.servlet;

import com.dao.BookDao;
import com.servlet.Book;
import com.untils.MysqlDB;

import java.util.ArrayList;
import java.util.List;

/**
 * BookDao接口实现
 */
public class BookDaoImpl implements BookDao {
    @Override
    public List<Book> select(String sql, Object[] arr) {
        MysqlDB.result = MysqlDB.query(sql);
        List<Book> list = new ArrayList<Book>();
        try {
            while (MysqlDB.result.next()){
                Book book = new Book();
                book.setId(MysqlDB.result.getInt("id"));
                book.setName(MysqlDB.result.getString("name"));
                book.setPrice(MysqlDB.result.getDouble("price"));
                list.add(book);
            }
            return  list;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MysqlDB.closeObject();
        }
        return null;
    }

    @Override
    public Book getBook(Integer id) {
        String sql = "select * from cart where id = ? ";
        MysqlDB.result = MysqlDB.query(sql,id);
        try {
            while (MysqlDB.result.next()){
                Book books = new Book();
                books.setId(MysqlDB.result.getInt("id"));
                books.setName(MysqlDB.result.getString("name"));
                books.setPrice(MysqlDB.result.getDouble("price"));
                return books;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MysqlDB.closeObject();
        }
        return null;
    }
}

实现接口:

package com.dao;

import com.servlet.Book;

import java.util.List;

public interface BookService {
    public List<Book> select(Book book);

    public Book getBook(Book book);
}

具体实现:

package com.servlet;

import com.dao.BookDao;
import com.dao.BookService;

import java.util.ArrayList;
import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao dao=new BookDaoImpl();
    @Override
    public List<Book> select(Book book) {
        StringBuilder  sql = new StringBuilder("select * from cart where 1=1") ;
        List<Object> list=new ArrayList<Object>();
        if(book!= null){
            if(book.getId() != null &&book.getId()!=0){
                sql.append("and id=?");
                System.out.println(sql);
                list.add(book.getId());
            }
        }
        return dao.select(sql.toString(), list.toArray());
    }

    @Override
    public Book getBook(Book book) {
        if(book.getId() != null &&book.getId()!=0){
            System.out.println("这个是BookServiceImpl的book.getID:"+book.getId());
             return dao.getBook(book.getId());
        }
        return null;
    }
}

接下来写jsp+servlet:

<%@ page import="java.util.Date" %>
<%@ page import="java.util.List" %>
<%@ page import="com.servlet.Book" %>
<%@ page import="com.servlet.BookServiceImpl" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-02-25
  Time: 13:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--图书列表显示页面-这里建议直接用El表达式写-%>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<div>
    <table>
        <tr><th>id</th><th>name</th><th>price</th><th>cart</th></tr>
        <%

            List<Book> list = (List<Book>) request.getAttribute("list");
            for(Book b:list){
        %>
        <tr align="center">
            <td><%=b.getId() %></td>
            <td><%=b.getName() %></td>
            <td><%=b.getPrice() %></td>
            <td><a href="add?id=<%=b.getId()%>">添加到购物车</a></td>
        </tr>
        <%} %>
    </table>
</div>
</body>
</html>

图书列表显示Servlet:

package com.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;
import java.util.List;

@WebServlet(name = "ShowServlet",value = "/showlist")
public class ShowServlet 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 {
        Book book = new Book();
        BookServiceImpl service = new BookServiceImpl();
        List<Book> list = service.select(book);
        request.setAttribute("list",list);
        request.getRequestDispatcher("/jsp/shoppinglist.jsp").forward(request,response);
    }
}

接下来我们写购物车,首先创建一个购物车实体类。存购物车信息和数量

package com.servlet;

/**
 * Cartitem实体类
 */
public class CartItem {
    private Book book;
    private Integer number;

    public CartItem() {

    }

    public CartItem(Book book, Integer number) {
        this.book = book;
        this.number = number;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
}

这里就是购物车的核心部分了:

package com.servlet;

import com.dao.BookService;

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.util.HashMap;
import java.util.Map;

@WebServlet(name = "addSeeionServlet",value = "/add")
public class addSeeionServlet 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 {
        Book book=new Book();
        //接收需要添加购物车的商品id
        String sid=request.getParameter("id");
        Integer id=Integer.parseInt(sid);
        BookService service=new BookServiceImpl();
        book.setId(id);
        Book books=service.getBook(book);
        HttpSession session = request.getSession();
        //判断session是否存在购物车
        Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
        if(cart == null){
        //若不存在则创建
            cart = new HashMap<>();
        }
        //考虑购物车是否存在该商品,
        CartItem cartItem = cart.get(books.getId());
        if(cartItem == null){
            cartItem = new CartItem();
            //若不存在,将该商品添加进购物车
            cartItem.setBook(books);
            //设初始数量为1
            cartItem.setNumber(1);
        }else{
        //若存在,则数量+1
            cartItem.setNumber(cartItem.getNumber()+1);
        }
        cart.put(books.getId(),cartItem);
        //将购物车存入Session
        session.setAttribute("cart",cart);
        request.getRequestDispatcher("/jsp/add.jsp").forward(request,response);
    }
}

购物车的展示页面:

<%@ page import="com.servlet.CartItem" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.servlet.Book" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-03-04
  Time: 17:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加商品</title>
</head>
<body>
添加完成
<table width="100%" align="center" border="1px">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>price</th>
        <th>count price</th>
        <th>unit cost</th>

    </tr>
    <%
        Map<Integer,CartItem> map=(Map<Integer,CartItem>)session.getAttribute("cart");
        //2:将购物车里面的内容遍历出来
        double count=0;//显示出总价格
        for(Map.Entry<Integer,CartItem> entry : map.entrySet()){
            //计算出每一样的书籍一共花了多少钱
            double price=entry.getValue().getBook().getPrice() * entry.getValue().getNumber();
            //计算出一共花了多少钱
            count=count+price;
    %>
    <tr align="center">
        <td><%=entry.getKey() %></td>
        <td><%=entry.getValue().getBook().getName() %></td>
        <td><%=entry.getValue().getBook().getPrice() %></td>
        <td><%=entry.getValue().getNumber() %></td>
        <td><%=entry.getValue().getBook().getPrice() * entry.getValue().getNumber()%></td>

    </tr>
    <%} %>
    <tr>
        <td colspan="4" align="right">价格总计</td>
        <td><%=count %></td>
    </tr>
</table>
</body>
</html>

这是一个非常简陋的购物车,还需要完善,加油!