为了方便用户下次登录,仍然可以看到自己的购物车内容,所以,需要在数据库存储相应的购物车项目,本处增加购物车项表;uid和bid是复合主键。

package com.cart.entity;
//购物车的单项;
public class CartItem {
	int uid;
	int bid; //外键;理解为商品id,这样可以任意;
	int count;
	String bookname;//方便存储
	double price; //单项价格;
	private String image;

	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public int getBid() {
		return bid;
	}
	public void setBid(int bid) {
		this.bid = bid;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getBookname() {
		return bookname;
	}
	public void setBookname(String bookname) {
		this.bookname = bookname;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}

	//有一个方法,获得总价;
	public double getTotalPrice(){
		return price*count;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getImage() {
		return image;
	}
}

//增加购物项
public interface CartDao {
	public int addCartItem(CartItem cartItem);
	public boolean isExists(int uid,int bid);
	public int updateCartItemCount(CartItem cartItem);
	public Map<Integer,CartItem> getCartItem(int uid);
	public CartItem findCartItemById(int uid,int bid);
}

package com.cart.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.cart.dao.CartDao;
import com.cart.entity.Book;
import com.cart.entity.CartItem;
import com.cart.util.DaoFactory;

public class CartDaoImpl implements CartDao {
	Connection con = null;
	PreparedStatement pstmt = null;
	ResultSet rs=null;
	public int addCartItem(CartItem cartItem) {
		String sql="insert cartitem values(?,?,?,?,?,?)";
		int result=-1;

		try {
			con=DaoFactory.getConnection();
			Object[]params={cartItem.getUid(),cartItem.getBid(),cartItem.getBookname(),cartItem.getPrice(),cartItem.getCount(),cartItem.getImage()};
			pstmt=con.prepareStatement(sql);
			DaoFactory.setParams(pstmt, params);
			result=DaoFactory.executeUpdate(sql, params);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return result;
	}

	/* 根据uid和bid进行判断是否已经有物品存在于否则,有则返回true,不用再插入了;
	 * @see com.cart.dao.CartDao#isExists(int, int)
	 */
	public boolean isExists(int uid,int bid) {
		String sql="select uid,bid from cartitem where uid=? and bid=?";
		boolean result=false;

		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[] params={uid,bid};
			DaoFactory.setParams(pstmt, params);
			rs=pstmt.executeQuery();
			if(rs.next()){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return result;
	}

	public int updateCartItemCount(CartItem cartItem) {
		String sql="update cartitem set count=? where uid=? and bid=?";
		int result=-1;
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[] params={cartItem.getCount(),cartItem.getUid(),cartItem.getBid()};
			DaoFactory.setParams(pstmt, params);
			result=pstmt.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}

		return result;
	}

	public Map<Integer, CartItem> getCartItem(int uid) {
		String sql="select * from cartitem where uid=?";
		Map<Integer,CartItem>cartItems=new HashMap<Integer,CartItem>();

		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[] params={uid};
			DaoFactory.setParams(pstmt, params);
			rs=pstmt.executeQuery();
			while(rs.next()){
				CartItem item=new CartItem();
				item.setUid(uid);
				int bid=rs.getInt("bid");
				item.setBid(bid);
				item.setBookname(rs.getString("bookname"));
				item.setCount(rs.getInt("count"));
				item.setPrice(rs.getDouble("price"));
				item.setImage(rs.getString("image"));

				cartItems.put(bid,item);//bid,后面是对应的item;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DaoFactory.closeAll(null, pstmt, con);
		}
		return cartItems;
	}

	public CartItem findCartItemById(int uid,int bid) {
		String sql = "select * from cartitem where uid=? and bid=?";
		ResultSet rs = null;
		CartItem item = null;
		try {
			con=DaoFactory.getConnection();
			pstmt=con.prepareStatement(sql);
			Object[] params={uid,bid};
			DaoFactory.setParams(pstmt, params);
			rs=pstmt.executeQuery();
			if(rs.next()){
				item = new CartItem();
				item.setUid(rs.getInt("uid"));
				item.setBookname(rs.getString("bookname"));
				item.setBid(rs.getInt("bid"));
				item.setCount(rs.getInt("count"));
				item.setPrice(rs.getDouble("price"));
				item.setImage(rs.getString("image"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			DaoFactory.closeAll(rs, pstmt, con);
		}
		return item;
	}

}

package com.cart.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cart.entity.Book;
import com.cart.entity.Cart;
import com.cart.entity.CartItem;
import com.cart.entity.Userinfo;
import com.cart.service.BookService;
import com.cart.service.CartService;

public class BuyServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		resp.setContentType("text/html;charset=utf-8");
		HttpSession session=req.getSession();

		Userinfo userinfo =(Userinfo)req.getSession().getAttribute("userinfo");
		int bid=Integer.parseInt(req.getParameter("id"));//这个就是bid
		//通过Service来获得book对象;
		BookService bookService=new BookService();
		Book book=bookService.getBookById(bid);
		//下一步,点击购物的时候,获得bid,+uid;1 1,则调出自己的购物车列表;
		CartService cartService=new CartService();
		int uid=userinfo.getId();
		Map<Integer,CartItem> cart=(Map<Integer,CartItem>)session.getAttribute("cart");
		//1.是已经存在于数据库的;
		if(cartService.isExists(uid, bid));//如果没有登录,已经过滤了;
		{
			//如果已经存在相当的数据,则应该读取出来到CartItem
			cart=cartService.getCartItem(uid);
		}
		//2.没有买过的;也没有登录过的;则新创建;
		//cart = (Map<Integer,CartItem>)session.getAttribute("cart");
		if(cart==null){
			cart=new HashMap<Integer,CartItem>();//id以及CartItem对象,这样购物车想可以是任意商品
			session.setAttribute("cart",cart);
		}

		//3.利用session登录,加入购物车了;但是没有到数据库的;
//
		CartItem cartItem=cart.get(bid);   //有4,但是数据库没有;

		if (cartItem == null) {
			cartItem=new CartItem();
			cartItem.setUid(userinfo.getId());
			cartItem.setBid(bid);// 此id为book的id;
			cartItem.setPrice(book.getPrice()); // 设置购物车项,图书的价格,升级要考虑会员的vip
			cartItem.setBookname(book.getBookname());
			cartItem.setCount(1); // 购物项完毕之后,需要将购物项放到一个购物车篮子中;
			cartItem.setImage(book.getImage());
		} else {
			// 判断是否已经是最后一本书;数量大于获得数量,其他的不能再加数量了
			if(book.getStock()>cartItem.getCount()){
				cartItem.setCount(cartItem.getCount()+1);
			}
		}
		//目前的问题是如果已经存在于数据库了,没有把cart的值给获取过来;
		cart.put(bid, cartItem);// 将购物车选项加进来!!!
		//同时设置购物车项进数据库,方便下次客户进来判断;

		//思路有问题f
		cartService.addCartItem(cartItem);
		//是否可以直接将cart插入到数据库中,对应某个该用户的id;
		session.setAttribute("cart", cart); //加入session用jstl读取;
		resp.sendRedirect("show_cart.jsp");
		//需要将购物车项加入到数据库中;
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'cart.jsp' starting page</title>

	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">

  <link rel="stylesheet" href="css/style.css" type="text/css"></link>

  <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>

  <script type="text/javascript">
  	function jian(id){
		if($("#count"+id).val()==1){
		//采用淘宝模式,如果低于1,则不用提示,直接不可用;
			$("#count"+id).prev().attribute("disabled","disabled");
			return;
		}

  		$.ajax({
  			url:'ChangeCartCountServlet',
  			type:'post',
  			dataType:'text',
  			data:{
  				bookid:id,
  				count:parseInt($("#count"+id).val())-1   //  -1
  			},
  			success:function(data){

 				var price = $("#price"+id).html();
		  		$("#count"+id).val(parseInt($("#count"+id).val())-1);
		  		$("#sum"+id).val("¥"+price*$("#count"+id).val());

		  		calcTotal();

  			}
  		});
  	}

  	function add(id){
  		$.ajax({
  			url:'ChangeCartCountServlet',
  			type:'post',
  			dataType:'text',
  			data:{
  				bookid:id,
  				count:parseInt($("#count"+id).val())+1
  			},
  			success:function(data){
  				if(data=="false"){
  					alert("库存不足!!!!");
  				}
  				else{
  					var price = $("#price"+id).html();
			  		$("#count"+id).val(parseInt($("#count"+id).val())+1);
			  		$("#sum"+id).val("¥"+price*$("#count"+id).val());

			  		calcTotal();
  				}
  			}
  		});

  	}

  	function calcTotal(){
  		// input...
  		var counts = $("input[id^=count]").toArray();
  		var prices = $("div[id^=price]").toArray();
  		var total = 0;

  		for(var i=0;i<prices.length;i++){
  			total += prices[i].innerHTML*counts[i].value;
  		}

  		$("#total").val("¥"+total);
  	}

  </script>

  </head>

  <body>
   <div id="header" class="wrap">
	<div id="banner"></div>
	<div id="navbar">
		<div class="userMenu">
			<ul>
				<li class="current"><font color="BLACK">欢迎您,<strong>andy</strong></font>   </li>
				<li><a href="index.jsp">首页</a></li>
				<li><a href="orderlist.html">我的订单</a></li>
				<li><a href="show_cart.jsp">购物车</a></li>
				<li><a href="logout.jsp">注销</a></li>
			</ul>
		</div>
	</div>
</div>
<div id="content" class="wrap">
	<div class="list bookList">
		<form method="post" name="shoping" action="">
			<table>
				<tr class="title">
					<th class="view">图片预览</th>
					<th>书名</th>
					<th class="nums">数量</th>
					<th class="price">价格</th>
					<th class="nums">合计</th>
					<th class="nums">操作</th>
				</tr>

					<c:set var="total" value="0"></c:set>

					<c:forEach items="${cart}" var="book">
					<tr>

						<td class="thumb">
						<img src="images/book/${book.value.image}" /></td>
						<td class="title">${book.value.bookname}</td>
						<td>
						<img src="images/edit_jian.png" width="12" height="12"
							onclick="jian(${book.value.bid})"/>

						<input id="count${book.value.bid}" readonly="readonly"
							value="${book.value.count}" size="2"/>

						<img src="images/edit_add.png" width="12" height="12"
						    onclick="add(${book.value.bid})"/>
						</td>

						<td>¥
							<div id="price${book.value.bid}" >${book.value.price}</div>
						</td>
						<td>
							<input id="sum${book.value.bid}"
							value='<fmt:formatNumber
								value="${book.value.count*book.value.price}"
								type="currency"></fmt:formatNumber>'
							/>

							<c:set var="total"
								value=
								"${total+book.value.count*book.value.price}"></c:set>

							<input type="hidden" name="items" value="10:2:31.6"/>
						</td>
						<td>
						<a href="DeleteCartItemServlet?bookid=${book.value.bid}">删除</a>
						</td>
					</tr>
					</c:forEach>

				<tr><td colspan="5">

			<div class="button">
				<h4>总价:
					<input id="total"
						value='<fmt:formatNumber value="${total}" type="currency"></fmt:formatNumber>'
					/>
				元</h4>
				<input type="hidden" id="hidden_total_price" name="hidden_total_price"/>
				<input class="input-chart" type="submit" name="submit" value="" />
			</div>
			</td></tr>

			</table>
		</form>
	</div>
</div>
</body>
	<div id="footer" class="wrap">
		网上书城 &copy; 版权所有
	</div>
</html>

</html>

package com.news.util;

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

//Dao工厂类
public class DaoFactory {
	private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=News";
	private static String user = "sa";
	private static String pwd = "123@qwe";

//	private static String driver="com.mysql.jdbc.Driver";
//	private static String url="jdbc:mysql://localhost:3306/news";
//    private static String user = "root" ;
//    private static String pwd = "admin" ;  

	// 1.公共方法是获得数据库链接对象
	public static Connection getConnection() {
		Connection con = null;
		try {
			Class.forName(driver);// 加,连
			con = DriverManager.getConnection(url, user, pwd);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;// 非void都需要return
	}
	// 2.关闭所有方法;有3个参数!,省代码了!!!
	public static void closeAll(ResultSet rs, Statement stmt, Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 3.setParams,用来设置预编译语句对象的?占位符的值;
	public static void setParams(PreparedStatement pstmt, Object[] params) {
		if (params == null) {
			return;
		}// return:直接返回,啥也不做;
		try {
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
		} catch (SQLException e) {// 有异常,加上去
			e.printStackTrace();
		}
	}

	// 4.做公共的更新方法,可以更新所有的基本sql语句;
	public int executeUpdate(String sql, Object[] params) {
		// 1.声明对象;是将来工作当中省内存;
		Connection con = null;
		PreparedStatement pstmt = null;
		int count = 0; // 增删改受影响的行数;

		try {
			con = this.getConnection();// 调用本类的方法;
			pstmt = con.prepareStatement(sql);// 建对象:预编译对象,?
			setParams(pstmt, params);// 调用设置?的方法,已经写过了!!!
			count = pstmt.executeUpdate();// 3.执行;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll(null, pstmt, con);
		}
		return count;
	}

	// 5.执行查询方法;
	public static List executeQuery(String sql, Object[] params) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int colCount = 0;
		ArrayList tableList=new ArrayList();//表集合

		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			setParams(pstmt, params);
			rs = pstmt.executeQuery();// 执行查询,结果给rs
			ResultSetMetaData rd = rs.getMetaData();// 获得元数据
			colCount = rd.getColumnCount();
			while (rs.next()) {
				ArrayList rowList = new ArrayList();//行集合
				for (int i = 1; i <= colCount; i++) {
					rowList.add(rs.getString(i));
				}
				tableList.add(rowList);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(rs,pstmt,con);
		}
		return tableList;
	}
}

jsp电子商务购物车之四 数据库存储篇的更多相关文章

  1. jsp电子商务购物车之五 数据库存储篇2

    业务逻辑图,简单版要写各个Servlet //ChangeCartCountServlet 使用ajax实现数量,增加或减少; package com.cart.web; import java.io ...

  2. jsp电子商务 购物车实现之一 设计篇

    购物车的功能实现. 查询的资料,找到三种方法: 1.用cookie实现购物车: 2.用session实现购物车: 3.用cookie和数据库(购物车信息持久化)实现购物车: ============= ...

  3. jsp电子商务 购物车实现之二 登录和分页篇

    登录页面核心代码 <div id="login"> <h2>用户登陆</h2> <form method="post" ...

  4. jsp电子商务 购物车实现之三 购物车

    CartServlet参考代码 : public void doPost(HttpServletRequest req, HttpServletResponse resp) throws Servle ...

  5. android之存储篇——SQLite数据库

    转载:android之存储篇_SQLite数据库_让你彻底学会SQLite的使用 SQLite最大的特点是你可以把各种类型的数据保存到任何字段中,而不用关心字段声明的数据类型是什么. 例如:可以在In ...

  6. Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用

    Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用 原创 2017-04-13 嘟嘟MD 嘟爷java超神学堂 前言 前面几章介绍了一些基础,但都是静 ...

  7. 时序数据库深入浅出之存储篇——本质LSMtree,同时 metric(比如温度)+tags 分片

    什么是时序数据库 先来介绍什么是时序数据.时序数据是基于时间的一系列的数据.在有时间的坐标中将这些数据点连成线,往过去看可以做成多纬度报表,揭示其趋势性.规律性.异常性:往未来看可以做大数据分析,机器 ...

  8. Sql Server来龙去脉系列之四 数据库和文件

        在讨论数据库之前我们先要明白一个问题:什么是数据库?     数据库是若干对象的集合,这些对象用来控制和维护数据.一个经典的数据库实例仅仅包含少量的数据库,但用户一般也不会在一个实例上创建太多 ...

  9. DDD开发框架ABP之本地化资源的数据库存储扩展

    在上一篇<DDD开发框架ABP之本地化/多语言支持>中,我们知道,ABP开发框架中本地化资源存储可以采用XML文件,RESX资源文件,也提供了其他自定义的存储方式的扩展接口.ABP框架默认 ...

随机推荐

  1. Python栈的学习资料

    持续更新... 1. 基础 Python for Everybody的视频课程,称得上深入浅出 https://www.py4e.com/ 2. 进阶 偏重实践应用,快速上手,稀饭~ https:// ...

  2. mybatis报表,动态列与查询参数+行列转换

    这是报表原型,在这张报表中,使用了动态的列与动态查询参数,动态列与动态查询参数全部使用map将参数传入 map参数: //拼接查询时间 for (String month : monthList) { ...

  3. (数据科学学习手札24)逻辑回归分类器原理详解&Python与R实现

    一.简介 逻辑回归(Logistic Regression),与它的名字恰恰相反,它是一个分类器而非回归方法,在一些文献里它也被称为logit回归.最大熵分类器(MaxEnt).对数线性分类器等:我们 ...

  4. SKIP(插入空行)

    WRITE 'This is the 1st line'. SKIP. WRITE 'This is the 2nd line'. 跳转至某一行 SKIP TO LINE line_number. 插 ...

  5. 10 TCP 传输控制协议 UDP区别

    1.tcp和udp区别 2.TCP通信模型 生活中的电话机 如果想让别人能更够打通咱们的电话获取相应服务的话,需要做一下几件事情: 买个手机 插上手机卡 设计手机为正常接听状态(即能够响铃) 静静的等 ...

  6. Python3: 对两个字符串进行匹配

    Python里一共有三种字符串匹配方式,用于判断一个字符串是否包含另一个字符串.比如判断字符串“HelloWorld”中是否包含“World”: def stringCompare(str1, str ...

  7. ACE学习综述(1)

    1. ACE学习综述 1.1. ACE项目的优点 可以跨平台使用,基本上可以实现一次编写,多平台运行. ACE本身不仅仅是一个简单的网络框架,对于网络框架涉及到的进程管理.线程管理等系统本身相关的内容 ...

  8. XPATH之normalize-space(.)和normalize-space(text())区别

    normalize,字面意思就是正规化,加上space大概意思就是空格的处理了. 官方解释是这样的: 通过去掉前导和尾随空白并使用单个空格替换一系列空白字符,使空白标准化.如果省略了该参数,上下文节点 ...

  9. LeetCode - 3. Longest Substring Without Repeating Characters(388ms)

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  10. LeetCode 81——搜索旋转排序数组 II

    1. 题目 2. 解答 2.1. 方法一 基于 LeetCode 33--搜索旋转排序数组 中的方法二. 当 nums[mid] = nums[right] 时,比如 [1, 1, 2, 1, 1], ...