分析:

提交订单功能,通过cart.jsp页面的“提交订单”a标签入口,进行功能操作,再显示到订单页面

这里关键点之一在于:搞清楚订单对象Order,订单项对象OrderItems,还有对应的orders表,与orderItem表。剩下的就是业务代码

根据表的内容,分别创建Orderr类,OrderItem类。

1.OrderItems对象对应orderItem表

  `itemid` varchar(32) NOT NULL,
  `count` int(11) DEFAULT NULL,
  `subtotal` double DEFAULT NULL,
  `pid` varchar(32) DEFAULT NULL,
  `oid` varchar(32) DEFAULT NULL,

2.Order对象对象orders表

  `oid` varchar(32) NOT NULL,
  `ordertime` datetime DEFAULT NULL,
  `total` double DEFAULT NULL,
  `state` int(11) DEFAULT NULL,
  `address` varchar(30) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `telephone` varchar(20) DEFAULT NULL,
  `uid` varchar(32) DEFAULT NULL,



2个类创建好之后,剩下的就是业务的操作。

看图(图是借用视频老师所画的)

提交java 提交订单_提交java

进入后台操作,需要判断session域中是否存在user对象,存在证明已经登陆,不存在,需要先登陆用户

1web:点击提交订单后,进入servlet,在web层主要工作为封装Order对象,因为Order对象包含时候数据库所需要的所有数据。

2service层,需要开启事务,因为订单与订单项的创建必须同时成功,才能成功的

3dao层,sql在orders表需要添加一个,代码执行一次,在orderitem表添加1个或多个,代码执行1此或多次


准备:

OrderItem对象

package com.itheima.domain;

public class OrderItem {
	//ordeItem表的数据
	 /* `itemid` varchar(32) NOT NULL,
	  `count` int(11) DEFAULT NULL,
	  `subtotal` double DEFAULT NULL,
	  `pid` varchar(32) DEFAULT NULL,
	  `oid` varchar(32) DEFAULT NULL,*/
	
	private String itemid;//订单项自己的id
	private int count;//购买的数量
	private double subtotal;//订单项的小计
	private Product product;//订单项内包含这一个product,面向对象思想
	private Order order;//订单项所属的订单对象order,面向对象思想
	public String getItemid() {
		return itemid;
	}
	public void setItemid(String itemid) {
		this.itemid = itemid;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public double getSubtotal() {
		return subtotal;
	}
	public void setSubtotal(double subtotal) {
		this.subtotal = subtotal;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	
	
}





Order对象

package com.itheima.domain;

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

public class Order {

	/*`oid` varchar(32) NOT NULL,
	  `ordertime` datetime DEFAULT NULL,
	  `total` double DEFAULT NULL,
	  `state` int(11) DEFAULT NULL,
	  `address` varchar(30) DEFAULT NULL,
	  `name` varchar(20) DEFAULT NULL,
	  `telephone` varchar(20) DEFAULT NULL,
	  `uid` varchar(32) DEFAULT NULL*/
	
	private String oid;//该订单的订单号
	private String ordertime;//下单时间,用String比较好的兼容mysql,注意封装时候格式转换为String
	private double total;//该订单的总金额
	private int state;//订单支付状态 1代表已付款 0代表未付款
	
	private String address;//收货地址
	private String name;//收货人
	private String telephone;//收货人电话
	
	private User user;//该订单属于哪个用户
	
	//该订单中有多少订单项
	List<OrderItem> orderItems = new ArrayList<OrderItem>();

	public String getOid() {
		return oid;
	}

	public void setOid(String oid) {
		this.oid = oid;
	}

	public String getOrdertime() {
		return ordertime;
	}

	public void setOrdertime(String ordertime) {
		this.ordertime = ordertime;
	}

	public double getTotal() {
		return total;
	}

	public void setTotal(double total) {
		this.total = total;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getName() {
		return name;
	}

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

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<OrderItem> getOrderItems() {
		return orderItems;
	}

	public void setOrderItems(List<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}
	
	
	
}




步骤:

在cart.jsp页面

1.在提交订单所在位置,修改a标签地址,作为入口进入后台代码操作

在ProductServlet

1.获取session域,判断客服是否已经登陆,没有登陆,跳转到登陆页面

2,web层任务是需要封装Order对象,创建一个order对象,进行封装oid,ordertime(需要转换器),name,address,telephone,uid,state

3.获取购车对象,获取购物车对象的购物项集合

4.遍历购物项集合,创建orderItem对象,根据遍历出购物项的数据,封装每一个orderitem,并存到order对象维护的容器orderItems里

5.封装order的最后一个属性 oredrItems,并把order传到service层。

6.把order存到session域(准备在订单页面显示订单信息)

7.重定向,把页面跳到订单页面order_info.jsp

ProductService

1.开启事务

2.把order传到dao层添加一个订单到数据库ordes表

3.把order传到dao层添加一个或多个订单项到数据库orderitem表

4.事务的rollback,释放

ProductDao

执行,涉及事务的 增加数据库信息操作。

order_info.jsp

1.通过order获取订单编号。

2.遍历order.orderItems,在页面显示订单项信息

3.友好体现,通过user,预先填写订单的收获地址,用户名,与电话

cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>    
<!DOCTYPE html>

<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>黑马商城购物车</title>
		<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
		<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
		<script src="js/bootstrap.min.js" type="text/javascript"></script>
		<!-- 引入自定义css文件 style.css -->
		<link rel="stylesheet" href="css/style.css" type="text/css" />
		<style>
			body {
				margin-top: 20px;
				margin: 0 auto;
			}
			
			.carousel-inner .item img {
				width: 100%;
				height: 300px;
			}
			
			font {
				color: #3164af;
				font-size: 18px;
				font-weight: normal;
				padding: 0 10px;
			}
		</style>
	</head>
	<script type="text/javascript">
		function delProFromCart(pid){
			if(confirm("您是否确定要删除")){
				location.href="${pageContext.request.contextPath}/product?method=delProFromCart&pid="+pid;
			}
		}
		
		function clearCart(){
			if(confirm("您是否确定清空购物车码")){
				location.href="${pageContext.request.contextPath}/product?method=clearCart";
			}
		}
		
	</script>
	
	<body>
		<!-- 引入header.jsp -->
		<jsp:include page="/header.jsp"></jsp:include>

		<!-- 判断购物车有商品 -->
		<c:if test="${!empty cart.cartItems }">
			<div class="container">
			<div class="row">
				<div style="margin:0 auto; margin-top:10px;width:950px;">
					<strong style="font-size:16px;margin:5px 0;">订单详情</strong>
					<table class="table table-bordered">
						<tbody>
							<tr class="warning">
								<th>图片</th>
								<th>商品</th>
								<th>价格</th>
								<th>数量</th>
								<th>小计</th>
								<th>操作</th>
							</tr>
							
							<c:forEach items="${cart.cartItems }" var="entry">
								<tr class="active">
								<td width="60" width="40%">
									<input type="hidden" name="id" value="22">
									<img src="${pageContext.request.contextPath }/${entry.value.product.pimage }" width="70" height="60">
								</td>
								<td width="30%">
									<a target="_blank">${entry.value.product.pname }</a>
								</td>
								<td width="20%">
									¥${entry.value.product.shop_price }
								</td>
								<td width="10%">
									${entry.value.buyNum }
								</td>
								<td width="15%">
									<span class="subtotal">¥${entry.value.subtotal }</span>
								</td>
								<td>
									<a href="javascript:void(0);" οnclick="delProFromCart('${entry.value.product.pid}')" class="delete">删除</a>
								</td>
							</tr>
							</c:forEach>
						</tbody>
					</table>
				</div>
			</div>
		</c:if>
		<!-- 购物车空的 -->
		<c:if test="${empty cart.cartItems }">
			<img alt="" src="${pageContext.request.contextPath}/images/cart-empty.png">
			<a href="${pageContext.request.contextPath}">返回首页</a>
		</c:if>
			<div style="margin-right:130px;">
				<div style="text-align:right;">
					<em style="color:#ff6600;">
				登录后确认是否享有优惠  
			</em> 赠送积分: <em style="color:#ff6600;">${cart.total }</em>  商品金额: <strong style="color:#ff6600;">¥${cart.total }元</strong>
				</div>
				<div style="text-align:right;margin-top:10px;margin-bottom:10px;">
					<a href="javacript:;" οnclick="clearCart()" id="clear" class="clear">清空购物车</a>
					<!-- 提交订单代码入口 -->
					<a href="${pageContext.request.contextPath }/product?method=submitOrder">
						<!-- 此处需要修改为button,因为submit没有所属form表单 -->
						<input type="button" width="100" value="提交订单" name="submit" border="0" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
						height:35px;width:100px;color:white;">
					</a>
				</div>
			</div>
		</div>

		<!-- 引入footer.jsp -->
		<jsp:include page="/footer.jsp"></jsp:include>

	</body>

</html>

ProductServlet

package com.itheima.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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

import com.google.gson.Gson;
import com.itheima.domain.Cart;
import com.itheima.domain.CartItem;
import com.itheima.domain.Category;
import com.itheima.domain.Order;
import com.itheima.domain.OrderItem;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.ProductService;
import com.itheima.utils.JedisPoolUtils;

import redis.clients.jedis.Jedis;

public class ProductServlet extends BaseServlet {

	// 提交订单
	public void submitOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取session域
		HttpSession session = request.getSession();
		// 获取user,判断用户是已经登陆
		User user = (User) session.getAttribute("user");
		if (user == null) {
			// 用户没有登陆跳转到登陆页面
			response.sendRedirect(request.getContextPath() + "/login.jsp");
			return;
		}
		// 封装Order对象
		// 创建Order对象,封装order对象所维护的属性
		Order order = new Order();
		// 1.private String oid;//订单自己所属id
		order.setOid(UUID.randomUUID().toString());
		// 2.private Date ordertime;//订单创建时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datestr = format.format(new Date());
		order.setOrdertime(datestr);
		// 3.private double total;//订单的总计
		// 获取购车对象cart,cart内有order所需要的很多属性
		Cart cart = (Cart) session.getAttribute("cart");
		double total = cart.getTotal();
		order.setTotal(total);
		// 4.private int state;//付款状态,---1代表已经付款,0代表还没有付款
		order.setState(0);
		// 5.private String address;//订单地址
		order.setAddress(null);
		// 6.private String name;//收获人姓名
		order.setName(null);
		// 7.private String telephone;//电话
		order.setTelephone(null);
		// 8.private User user;//创建订单的用户
		order.setUser(user);
		
		// 9.封装订单项集合 private List<OrderItem> orderItems = new ArrayList<OrderItem>();
		//订单项集合的每个订单项起始就是购物车中的每个购物项
		// 获取购物车项集合
		Map<String, CartItem> cartItems = cart.getCartItems();
		// 遍历购车项集合
		for(Map.Entry<String,CartItem> entry :cartItems.entrySet()) {
			//获取购物车项
			CartItem cartItem = entry.getValue();
			//封装每一个订单项
			OrderItem orderItem = new OrderItem();
			//封装购买数量
			orderItem.setCount(cartItem.getBuyNum());
			//封装订单项id
			orderItem.setItemid(UUID.randomUUID().toString());
			//封装订单项商品
			orderItem.setProduct(cartItem.getProduct());
			//封装订单项小计
			orderItem.setSubtotal(cartItem.getSubtotal());
			//封装订单项所属的订单
			orderItem.setOrder(order);
			//存储每一个订单项
			order.getOrderItems().add(orderItem);
		}
		//到此为止order对象总算封装完成
		
		//把order传到service层
		ProductService service = new ProductService();
		service.submitOrder(order);
		//把order存到session
		session.setAttribute("order", order);
		
		//重定向到订单页面
		response.sendRedirect(request.getContextPath()+"/order_info.jsp");
		

	}

	// 清空购物车
	public void clearCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("cart");
		// 跳转回cart.jsp
		response.sendRedirect(request.getContextPath() + "/cart.jsp");
	}

	// 在购物车删除购物项
	public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取pid
		String pid = request.getParameter("pid");
		// 获取购物车项
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart != null) {
			Map<String, CartItem> cartItems = cart.getCartItems();
			// 修改cart的总计
			double total = cart.getTotal() - cartItems.get(pid).getSubtotal();
			cart.setTotal(total);
			// 删除购物项
			cartItems.remove(pid);
		}
		// 跳转回cart.jsp
		response.sendRedirect(request.getContextPath() + "/cart.jsp");

	}

	// 将商品添加到购物车
	public void addProductToCart(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		ProductService service = new ProductService();
		// 获得放在购物车商品的pid
		String pid = request.getParameter("pid");
		// 获得这次商品的购买数
		int buyNum = Integer.parseInt(request.getParameter("buyNum"));
		// 获得paoduct对象
		Product product = service.findProductByPid(pid);
		// 计算这次小计
		double subtotal = product.getShop_price() * buyNum;
		/*
		 * //封装cartItem CartItem carItem = new CartItem(); carItem.setBuyNum(buyNum);
		 * carItem.setProduct(product); carItem.setSubtotal(subtotal);
		 */

		// 获取购物车,判断session中是否已经有购物车 ,没有就创建
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
		}
		// 将购物项放到车中---key是pid
		// 先判断购物车中是否已将包含此购物项了 ----- 判断key是否已经存在
		// 如果购物车中已经存在该商品----将现在买的数量与原有的数量进行相加操作、
		Map<String, CartItem> cartItems = cart.getCartItems();
		double newSubtotal = product.getShop_price() * buyNum;
		if (cartItems.containsKey(pid)) {
			// 购物车已经有该商品
			// 获取之前的购物车项
			CartItem oldCartItem = cartItems.get(pid);
			// 之前和现在相加后的最后购买数量
			buyNum = oldCartItem.getBuyNum() + buyNum;
			// 之前和现在相加后的最后购买小计
			newSubtotal = oldCartItem.getSubtotal() + subtotal;
		}
		// 封装最终的购物车项
		CartItem carItem = new CartItem();
		carItem.setBuyNum(buyNum);
		carItem.setProduct(product);
		carItem.setSubtotal(newSubtotal);

		// 将购物项存到购物车中
		cartItems.put(pid, carItem);
		// 计算计算购物车总计
		double total = cart.getTotal() + subtotal;
		cart.setTotal(total);

		// 车再次放回session
		session.setAttribute("cart", cart);
		// 直接跳转到购物车页面
		response.sendRedirect(request.getContextPath() + "/cart.jsp");
	}

	// 1.获取商品分类列表
	public void categoryList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProductService service = new ProductService();
		/*
		 * 有redis服务器的情况下// 先从缓存查看是否存在categoryList 如果没有从数据库查找,再存到redis缓存,如果有,直接调用 Jedis
		 * jedis = JedisPoolUtils.getJedis(); String categoryListJson =
		 * jedis.get("categoryListJson"); if (categoryListJson == null) {
		 * System.out.println("缓存没有数据,查找数据库"); // 获取商品分类 List<Category> categoryList =
		 * service.findAllCategory(); Gson gson = new Gson(); categoryListJson =
		 * gson.toJson(categoryList); jedis.set("categoryListJson", categoryListJson); }
		 */

		// 获取商品分类
		List<Category> categoryList = service.findAllCategory();
		Gson gson = new Gson();
		String categoryListJson = gson.toJson(categoryList);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(categoryListJson);
	}

	// 2.获取热门商品与最新商品集合
	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductService service = new ProductService();
		// 获取热门商品
		List<Product> hotProductList = service.findHotProduct();
		// 获取最新商品
		List<Product> newProductList = service.findNewProduct();
		// 把集合传到域
		request.setAttribute("hotProductList", hotProductList);
		request.setAttribute("newProductList", newProductList);
		// 转发
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	// 3.商品详细信息页面
	public void productInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取pid
		String pid = request.getParameter("pid");
		String cid = request.getParameter("cid");
		String currentPage = request.getParameter("currentPage");
		ProductService service = new ProductService();
		// 根据pid查询商品
		Product product = service.findProductByPid(pid);
		// 根据cid查询分类
		Category category = service.findCategoryByPid(cid);
		// 传到request域,转发
		request.setAttribute("category", category);
		request.setAttribute("product", product);
		request.setAttribute("cid", cid);
		request.setAttribute("currentPage", currentPage);
		// 获得客户端携带的cookie 获得名字pids的cookie
		// 转发前创建cookie,存储pid
		String pids = pid;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if ("pids".equals(cookies[i].getName())) {
					pids = cookies[i].getValue();
					String[] split = pids.split("-");
					List<String> asList = Arrays.asList(split);
					LinkedList<String> list = new LinkedList<String>(asList);
					// 判断当前集合是否包含现在的pid
					if (list.contains(pid)) {
						// 包含当前商品的pid
						list.remove(pid);
						list.addFirst(pid);
					} else {
						// 不包含当前pid
						list.addFirst(pid);
					}
					// 将集合转为字符串[3,1,2]转为3-1-2
					StringBuffer sb = new StringBuffer();
					for (int j = 0; j < list.size(); j++) {
						sb.append(list.get(j));
						sb.append("-");
					}
					// 去掉最后的-
					pids = sb.substring(0, sb.length() - 1);
				}
			}
		}
		Cookie cookie_pids = new Cookie("pids", pids);
		response.addCookie(cookie_pids);
		request.getRequestDispatcher("/product_info.jsp").forward(request, response);
	}

	// 4.根据分类cid获取商品集合
	public void productListByCid(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得cid
		String cid = request.getParameter("cid");
		// 获取当前页
		String currentPageStr = request.getParameter("currentPage");
		if (currentPageStr == null) {
			currentPageStr = "1";
		}
		int currentPage = Integer.parseInt(currentPageStr);
		int currentCount = 12;
		// 根据cid找pageBean
		ProductService service = new ProductService();
		PageBean pageBean = service.getPageBeanByCid(cid, currentPage, currentCount);
		// 定义一个手机历史商品的集合
		ArrayList<Product> histroyProductList = new ArrayList<Product>();
		// 获得客户端携带的名为pids的cookie
		Cookie[] cookies = request.getCookies();
		// 获取浏览过的商品
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("pids".equals(cookie.getName())) {
					String pids = cookie.getValue();
					String[] split = pids.split("-");
					for (int i = 0; i < split.length && i < 7; i++) {
						Product product = service.findProductByPid(split[i]);
						histroyProductList.add(product);
					}
				}
			}
		}
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("cid", cid);
		request.setAttribute("histroyProductList", histroyProductList);
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
	}

}

ProductService

package com.itheima.service;

import java.sql.SQLException;
import java.util.List;

import com.itheima.dao.ProductDao;
import com.itheima.domain.Category;
import com.itheima.domain.Order;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;
import com.itheima.utils.DataSourceUtils;

public class ProductService {

	// 获取热门商品
	public List<Product> findHotProduct() {
		ProductDao dao = new ProductDao();
		List<Product> hotProductList = null;
		try {
			hotProductList = dao.findHotProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return hotProductList;
	}

	// 获取最新商品
	public List<Product> findNewProduct() {
		ProductDao dao = new ProductDao();
		List<Product> newProductList = null;
		try {
			newProductList = dao.findNewProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return newProductList;
	}

	// 获得商品分类
	public List<Category> findAllCategory() {
		ProductDao dao = new ProductDao();
		List<Category> categoryList = null;
		try {
			categoryList = dao.findAllCategory();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return categoryList;
	}

	// 根据cid获得商品列表,并封装pageBean
	public PageBean getPageBeanByCid(String cid, int currentPage, int currentCount) {
		ProductDao dao = new ProductDao();
		PageBean<Product> pageBean = new PageBean<Product>();
		// 当前页
		pageBean.setCurrentPage(currentPage);
		// 当前页显示条数
		pageBean.setCurrentCount(currentCount);
		// 总共条数
		int totalCount = 0;
		try {
			totalCount = dao.findTotalCount(cid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setTotalCount(totalCount);
		// 总共页数
		int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
		pageBean.setTotalPage(totalPage);
		// 商品list
		int index = (currentPage - 1) * currentCount;
		List<Product> list = null;
		try {
			list = dao.findProductByCid(cid, index, currentCount);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setList(list);
		return pageBean;
	}

	// 根据pid查询商品
	public Product findProductByPid(String pid) {
		ProductDao dao = new ProductDao();
		Product product = null;
		try {
			product = dao.findProductByPid(pid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return product;
	}

	// 根据cid查询分类
	public Category findCategoryByPid(String cid) {
		ProductDao dao = new ProductDao();
		Category category = null;
		try {
			category = dao.findCategoryByPid(cid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return category;
	}

	// 提交订单,把订单,订单项存到数据库
	public void submitOrder(Order order)   {
		ProductDao dao = new ProductDao();
		try {
			// 1.开启事务
			DataSourceUtils.startTransaction();
			//2.存储order的方法
			dao.addOrders(order);
			//3.存储orderItem的方法
			dao.addOrderItem(order);
			
		} catch (SQLException e) {
			try {
				DataSourceUtils.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			try {
				DataSourceUtils.commitAndRelease();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

ProductDao

package com.itheima.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.itheima.domain.Category;
import com.itheima.domain.Order;
import com.itheima.domain.OrderItem;
import com.itheima.domain.Product;
import com.itheima.utils.DataSourceUtils;

public class ProductDao {

	//获取热门商品
	public List<Product> findHotProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from product where is_hot=? limit ?,?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class), 1,0,9);
	}

	//获取最新商品
	public List<Product> findNewProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from product order by pdate desc limit ?,?";
		return runner.query(sql, new BeanListHandler<Product>(Product.class),0,9);
	}
	
	//获得商品分类
	public List<Category> findAllCategory() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from category";
		return runner.query(sql, new BeanListHandler<Category>(Category.class));
	}

	//获取总共条数
	public int findTotalCount(String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select count(*) from product where cid=?";
		Long query = (Long) runner.query(sql, new ScalarHandler(), cid);
		return query.intValue();
	}

	//根据cid获取商品
	public List<Product> findProductByCid(String cid, int index, int currentCount) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from product where cid=? limit ?,?";
		List<Product> query = runner.query(sql, new BeanListHandler<Product>(Product.class), cid,index,currentCount);
		return query;
	}

	//根据pid查询商品
	public Product findProductByPid(String pid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from product where pid=?";
		Product query = runner.query(sql, new BeanHandler<Product>(Product.class), pid);
		return query;
	}

	//根据cid查询分类
	public Category findCategoryByPid(String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from category where cid=?";
		Category query = runner.query(sql, new BeanHandler<Category>(Category.class), cid);
		return query;

	}

	//向orders表插入数据
		public void addOrders(Order order) throws SQLException {
			QueryRunner runner = new QueryRunner();
			String sql = "insert into orders values(?,?,?,?,?,?,?,?)";
			Connection conn = DataSourceUtils.getConnection();
			runner.update(conn,sql, order.getOid(),order.getOrdertime(),order.getTotal(),order.getState(),
					order.getAddress(),order.getName(),order.getTelephone(),order.getUser().getUid());
		}
	
	//添加订单项到数据库
	public void addOrderItem(Order order) throws SQLException {
		QueryRunner runner = new QueryRunner();
		String sql = "insert into orderitem values(?,?,?,?,?)";
		Connection connection = DataSourceUtils.getConnection();
		//获取订单项集合,遍历,存到数据库中
		List<OrderItem> orderItems = order.getOrderItems();
		for(OrderItem orderItem:orderItems) {
			runner.update(connection, sql, orderItem.getItemid(),orderItem.getCount(),orderItem.getSubtotal(),
					orderItem.getProduct().getPid(),orderItem.getOrder().getOid());
		}
	}

}

order_info.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>	
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>会员登录</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="css/style.css" type="text/css" />
<style>
body {
	margin-top: 20px;
	margin: 0 auto;
}

.carousel-inner .item img {
	width: 100%;
	height: 300px;
}
</style>
</head>

<body>
	<!-- 引入header.jsp -->
	<jsp:include page="/header.jsp"></jsp:include>
	
	<div class="container">
		<div class="row">
			<div style="margin: 0 auto; margin-top: 10px; width: 950px;">
				<strong>订单详情</strong>
				<table class="table table-bordered">
					<tbody>
						<tr class="warning">
							<th colspan="5">订单编号:${order.oid }</th>
						</tr>
						<tr class="warning">
							<th>图片</th>
							<th>商品</th>
							<th>价格</th>
							<th>数量</th>
							<th>小计</th>
						</tr>
						<!-- 遍历获取订单项 -->
						<c:forEach items="${order.orderItems }" var="orderItem">
							<tr class="active">
								<td width="60" width="40%"><input type="hidden" name="id"
									value="22"> <img src="${pageContext.request.contextPath}/${orderItem.product.pimage}" width="70"
									height="60"></td>
								<td width="30%"><a target="_blank">${orderItem.product.pname}</a></td>
								<td width="20%">¥${orderItem.product.shop_price}</td>
								<td width="10%">${orderItem.count}</td>
								<td width="15%"><span class="subtotal">¥${orderItem.subtotal}</span></td>
							</tr>
						</c:forEach>
					</tbody>
				</table>
			</div>

			<div style="text-align: right; margin-right: 120px;">
				商品金额: <strong style="color: #ff6600;">¥${order.total }元</strong>
			</div>

		</div>

		<div>
			<hr />
			<form class="form-horizontal"
				style="margin-top: 5px; margin-left: 150px;">
				<div class="form-group">
					<label for="username" class="col-sm-1 control-label">地址</label>
					<div class="col-sm-5"> 
						<input type="text" class="form-control" id="username"
							placeholder="请输入收货地址">
					</div>
				</div>
				<div class="form-group">
					<label for="inputPassword3" class="col-sm-1 control-label">收货人</label>
					<div class="col-sm-5">
						<input type="text" class="form-control" id="inputPassword3" value="${user.name }"
							placeholder="请输收货人">
					</div>
				</div>
				<div class="form-group">
					<label for="confirmpwd" class="col-sm-1 control-label">电话</label>
					<div class="col-sm-5">
						<input type="text" class="form-control" id="confirmpwd" value="${user.telephone }"
							placeholder="请输入联系方式">
					</div>
				</div>
			</form>

			<hr />

			<div style="margin-top: 5px; margin-left: 150px;">
				<strong>选择银行:</strong>
				<p>
					<br /> <input type="radio" name="pd_FrpId" value="ICBC-NET-B2C"
						checked="checked" />工商银行 <img src="./bank_img/icbc.bmp"
						align="middle" />     <input type="radio"
						name="pd_FrpId" value="BOC-NET-B2C" />中国银行 <img
						src="./bank_img/bc.bmp" align="middle" />    
					<input type="radio" name="pd_FrpId" value="ABC-NET-B2C" />农业银行 <img
						src="./bank_img/abc.bmp" align="middle" /> <br /> <br /> <input
						type="radio" name="pd_FrpId" value="BOCO-NET-B2C" />交通银行 <img
						src="./bank_img/bcc.bmp" align="middle" />    
					<input type="radio" name="pd_FrpId" value="PINGANBANK-NET" />平安银行
					<img src="./bank_img/pingan.bmp" align="middle" />    
					<input type="radio" name="pd_FrpId" value="CCB-NET-B2C" />建设银行 <img
						src="./bank_img/ccb.bmp" align="middle" /> <br /> <br /> <input
						type="radio" name="pd_FrpId" value="CEB-NET-B2C" />光大银行 <img
						src="./bank_img/guangda.bmp" align="middle" />    
					<input type="radio" name="pd_FrpId" value="CMBCHINA-NET-B2C" />招商银行
					<img src="./bank_img/cmb.bmp" align="middle" />

				</p>
				<hr />
				<p style="text-align: right; margin-right: 100px;">
					<a href="javascript:document.getElementById('orderForm').submit();">
						<img src="./images/finalbutton.gif" width="204" height="51"
						border="0" />
					</a>
				</p>
				<hr />

			</div>
		</div>

	</div>

	<!-- 引入footer.jsp -->
	<jsp:include page="/footer.jsp"></jsp:include>

</body>

</html>