<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>书城首页</title>
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
<link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<body>
<div id="header">
<img class="logo_img" alt="" src="static/img/logo.gif" width="230px" height="80px">
<span class="wel_word">网上书城</span>
<div>
<c:choose>
<c:when test="${empty sessionScope.user}">
<a href="pages/user/login.jsp">登录</a> |
<a href="pages/user/regist.jsp">注册</a>
</c:when>
<c:otherwise>
<span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临网上书城</span>
<a href="UserServlet?method=logout">注销</a>
</c:otherwise>
</c:choose>
<a href="pages/cart/cart.jsp">购物车</a>
<a href="pages/manager/manager.jsp">后台管理</a>
</div>
</div>
<div id="main">
<div id="book">
<div class="book_cond" style="margin-left: 0px;text-align: center">
<form id="fid">
<input type="hidden" name="method" value="searchPage">
书名:<input type="text" name="name" value="${requestScope.name}">
作者:<input type="text" name="author" value="${requestScope.author}">
价格:<input id="min" type="text" name="min" value="${requestScope.min}"> 元 -
<input id="max" type="text" name="max" value="${requestScope.max}"> 元
<input type="button" value="查询" id="searchBut"/>
</form>
</div>
<div style="text-align: center;visibility: hidden;" id="cartdiv">
<span>您的购物车中有<span style="color: red" id="bookCount"></span>件商品</span>
<div>
您刚刚将<span style="color: red" id="bookName"></span>加入到了购物车中
</div>
</div>
<div class="b_list" style="display: none;" >
<div class="img_div">
<img class="book_img" alt="" src="${b.imgPath}"/>
</div>
<div class="book_info">
<div class="book_name">
<span class="sp1">书名:</span>
<span class="sp2">${b.name}</span>
</div>
<div class="book_author">
<span class="sp1">作者:</span>
<span class="sp2">${b.author}</span>
</div>
<div class="book_price">
<span class="sp1">价格:</span>
<span class="sp2">¥${b.price}</span>
</div>
<div class="book_sales">
<span class="sp1">销量:</span>
<span class="sp2">${b.sales}</span>
</div>
<div class="book_amount">
<span class="sp1">库存:</span>
<span class="sp2">${b.stock}</span>
</div>
<div class="book_add">
<input type="button" value="加入购物车" class="addToCart" bookId="${b.id}"/>
</div>
</div>
</div>
</div>
<!-- jsp动态包含 -->
<%-- <jsp:include page="pages/component/paging.jsp"></jsp:include>--%>
<div id="demo7"></div>
</div>
<div id="bottom">
<span>
网上书城.Copyright ©2020
</span>
</div>
</body>
</html>
<link type="text/css" rel="stylesheet" href="static/css/style.css">
<script src="static/script/jquery-3.6.0.min.js"></script>
<script src="static/layui/layui.js"></script>
<script>
layui.use(['laypage', 'layer'], function(){
var laypage = layui.laypage
,layer = layui.layer;
//完整功能
laypage.render({
elem: 'demo7'
,count: 100
,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
,jump: function(obj){
console.log(obj)
}
});
});
</script>
<script>
$(function(){
$("input.addToCart").click(function(){
if( "${sessionScope.user}" == "" ){
layer.msg('请先登录在来添加购物车!', {
icon: 2,
time: 2000 //2秒关闭(如果不配置,默认是3秒)
});
}else{
var id = $(this).attr("bookId");
$.get("CartServlet","method=addItem&id="+id,function (msg){
// alert( msg.bookName + " = " + msg.bookCount)
$("#bookCount").html(msg.bookCount);
$("#bookName").html(msg.bookName)
$("#cartdiv").css("visibility" , "");//显示出来
layer.msg('添加购物车成功', {
icon: 1,
time: 2000 //2秒关闭(如果不配置,默认是3秒)
});
});
}
});
});
</script>
这是主要的jsp文件,然后在突出一下重点:
<script>
$(function(){
$("input.addToCart").click(function(){
if( "${sessionScope.user}" == "" ){
layer.msg('请先登录在来添加购物车!', {
icon: 2,
time: 2000 //2秒关闭(如果不配置,默认是3秒)
});
}else{
var id = $(this).attr("bookId");
$.get("CartServlet","method=addItem&id="+id,function (msg){
// alert( msg.bookName + " = " + msg.bookCount)
$("#bookCount").html(msg.bookCount);
$("#bookName").html(msg.bookName)
$("#cartdiv").css("visibility" , "");//显示出来
layer.msg('添加购物车成功', {
icon: 1,
time: 2000 //2秒关闭(如果不配置,默认是3秒)
});
});
}
});
});
</script>
第一个功能很简单,就是单纯看看是否登录,如果没有登录,点击了添加购物车是会提示信息的,如下图:
下面一个功能是添加购物车成功
这个cartitem在之前的文章中有创建过,所以在这里不在赘述
使用ajax实现二级联动
这里给出关键的cartitem的代码
CartServlet .java
package com.softeem.servlet;
import com.google.gson.Gson;
import com.softeem.bean.Book;
import com.softeem.bean.CartItem;
import com.softeem.bean.User;
import com.softeem.service.BookService;
import com.softeem.service.CartItemService;
import com.softeem.service.impl.BookServiceImpl;
import com.softeem.service.impl.CartItemServiceImpl;
import com.softeem.utils.BaseServlet;
import com.softeem.utils.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
@WebServlet(value="/CartServlet")
public class CartServlet extends BaseServlet {
protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CartItemService cartItemService = new CartItemServiceImpl();
// 获取请求的参数 商品编号bookId
int bookId = WebUtils.parseInt(req.getParameter("id"), 0);
//从session会话作用域中获取用户的主键id
User user = (User)req.getSession().getAttribute("user");
CartItem cart = new CartItem(null, null,1 ,null, null, user.getId());
//返回封装了商品件数与图书名称的map
Map map =cartItemService.addItem(cart,bookId);
Gson gson = new Gson();
//将map 转换成 json 字符串
String str = gson.toJson(map);
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.print(str);
}
}
CartItemService .java
package com.softeem.service;
import com.softeem.bean.CartItem;
import java.util.Map;
public interface CartItemService {
public Map addItem(CartItem cartItem, Integer bookId);
public void deleteItem(Integer id);
public void clear(Integer uid);
public void updateCount(Integer id,Integer count , Double totalPrice);
public CartItem findByNameAndUid(String name,Integer uid);
}
CartItemServiceImpl .java
package com.softeem.service.impl;
import com.softeem.bean.Book;
import com.softeem.bean.CartItem;
import com.softeem.dao.BookDao;
import com.softeem.dao.CartItemDao;
import com.softeem.dao.impl.BookDaoImpl;
import com.softeem.dao.impl.CartItemDaoImpl;
import com.softeem.service.CartItemService;
import java.util.HashMap;
import java.util.Map;
public class CartItemServiceImpl implements CartItemService {
private CartItemDao cartItemDao = new CartItemDaoImpl();
private BookDao bookDao = new BookDaoImpl() ;
@Override
public Map addItem(CartItem cartItem , Integer bookId) {
//通过bookId查询book图书对象
Book book = bookDao.queryBookById(bookId);
//通过图书名与用户主键id可以查询到具体某一个<购物车项>
CartItem cart = cartItemDao.findByNameAndUid(book.getName(), cartItem.getUid());
//购物车项是不是空的.如果是空的就证明,该用户之前没有添加过此商品
if(cart != null){
//如果不等于空.那么此商品已经被该用户添加到购物车中,所以我们只用更新一下商品数量与商品总价即可
cart.setCount( cart.getCount() + 1 );
cart.setTotalPrice( cart.getCount() * cart.getPrice() );
//执行update,修改商品数量与总价
cartItemDao.updateCartCountById(cart.getId() , cart.getCount() , cart.getTotalPrice());
}else {
//否则该用户之前并没有添加过此商品到购物车,所以我们要创建一个<购物车项>对象.并且添加到数据库中
cartItem.setName(book.getName());
cartItem.setPrice(book.getPrice());
cartItem.setTotalPrice(cartItem.getCount()*cartItem.getPrice());
//执行insert 添加一个全新的<购物车项>
cartItemDao.addCart(cartItem);
}
Map map = new HashMap();
//通过用户uid查询此用户购物车中的商品件数
Integer count = cartItemDao.findByUidCount(cartItem.getUid());
map.put("bookCount" , count);//将商品件数保存到map中
map.put("bookName" , book.getName());//将图书名称保存到map中
return map;
}
@Override
public void deleteItem(Integer id) {
cartItemDao.deleteCartById(id);
}
@Override
public void clear(Integer uid) {
cartItemDao.deleteCartByUid(uid);
}
@Override
public void updateCount(Integer id, Integer count,Double totalPrice) {
cartItemDao.updateCartCountById(id,count,totalPrice);
}
@Override
public CartItem findByNameAndUid(String name, Integer uid) {
return cartItemDao.findByNameAndUid(name,uid);
}
}
CartItemDao .java
package com.softeem.dao;
import com.softeem.bean.CartItem;
public interface CartItemDao {
public int addCart(CartItem cartItem);
public int deleteCartById(Integer id);
public int deleteCartByUid(Integer uid);
public int updateCartCountById(
Integer id,Integer count,Double totalPrice);
public CartItem findByNameAndUid(String name,Integer uid);
public Integer findByUidCount(Integer uid);
}
CartItemDaoImpl .java
package com.softeem.dao.impl;
import com.softeem.bean.CartItem;
import com.softeem.dao.CartItemDao;
import com.softeem.utils.BaseDao;
public class CartItemDaoImpl extends BaseDao<CartItem> implements CartItemDao {
public int addCart(CartItem cartItem) {
return this.update("insert into cartitem values(null,?,?,?,?,?)",
cartItem.getName(), cartItem.getCount(), cartItem.getPrice(),
cartItem.getTotalPrice(), cartItem.getUid()
);
}
@Override
public int deleteCartById(Integer id) {
return this.update("delete from cartitem where id=?", id);
}
@Override
public int deleteCartByUid(Integer uid) {
return this.update("delete from cartitem where uid=?", uid);
}
@Override
public int updateCartCountById(Integer id, Integer count, Double totalPrice) {
return this.update("update cartitem set count = ?,total_price=? where id = ?", count, totalPrice, id);
}
@Override
public CartItem findByNameAndUid(String name, Integer uid) {
return this.getBean("select * from cartitem where name=? and uid=?", name, uid);
}
@Override
public Integer findByUidCount(Integer uid) {
return this.getValue("select count(*) from cartitem where uid=?", uid).intValue();
}
}
实现的效果图: