1. 程式人生 > >Shop專案--12. 顯示使用者訂單列表order_list.jsp

Shop專案--12. 顯示使用者訂單列表order_list.jsp

分析:

顯示使用者訂單列表在order_list.jsp頁面,要一個功能servlet,把資料傳遞給前臺頁面顯示。同時要先判斷使用者是否已經登陸。關鍵在於資料需要怎麼封裝,這裡涉及多表查詢。


1.根據uid,查詢使用者的所有訂單集合List<Order>。此時order物件裡資料orderItem集合還沒有封裝好,需要遍歷封裝資料

2.判斷List<Order>是否為空,如不為空,進行遍歷,並進行多表查詢。查詢orderItem表的count,subtotal,查詢product表的pimage,pname,shop_price。

select i.count,i.subtotal,p.pimage,p.pname,p.shop_price  from orderItem i, product p where i.pid=p.pid and oid=?

因為查詢過後的資料,不能用orderitem或product泛型直接封裝。所以需要用MapListHandler來裝查詢之後的資料。意在於把count,subtotal,pimage,paneme,shop_price封到一起,然後下一步再查出來封裝。


多表查詢返回後的是List<Map<String,object>> mapList 。根據mapList裡的count subtatol pimage pname shop_price 封裝OrderItem物件與Product物件。 

然後把Product物件封裝到OrderItem物件裡,再把OrderItem物件封裝到Order物件的List<OrderItem>集合裡。這樣,一個所需要的Order物件封裝完畢。

3把orderList傳到request域,並轉發到order_list.jsp

在order_list.jsp頁面

匯入jstl

1.遍歷orderList,得到每個order物件。可以獲取訂單編號,訂單付款狀態,訂單總計

2.遍歷每個訂單物件的訂單項集合orderItems,得到每個訂單下的每個訂單項orderItem,獲取count,subtotal,pimage,shop_price

步驟:

在head.jsp頁面,修改“我的訂單”的href。作為servlet入口

ProductServlet

0.判斷user是否已經登陸。

1.查詢該使用者下的所有訂單List<Order> orderList,此時資料還沒有封裝完畢,需要補充資料。

2.遍歷orderList,多表查詢orderitem product表

3.根據oid, 查詢orderItems表,與有關聯的product表

4.把mapList轉換為List<OrderItem> OrderItems 

從map中抽取piame paname shop_price封裝到product中

從map中抽取count subtotal封裝到orderItem裡

將product封裝到orderitem中

把orderItem物件封裝到order物件的集合裡

5.到目前為止,order物件封裝完畢,把orderList轉發到訂單顯示頁面order_list.jsp

在order_list.jsp

匯入jstl

1.遍歷orderList,得到order,通過order獲取oid total state

2.遍歷order裡面的orderItems.得到orderItem,通過orderItem獲取count subtotal pimage pname shop_price.

head.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>
<!-- 登入 註冊 購物車... -->
<div class="container-fluid">
	<div class="col-md-4">
		<img src="img/logo2.png" />
	</div>
	<div class="col-md-5">
		<img src="img/header.png" />
	</div>
	<div class="col-md-3" style="padding-top:20px">
		<ol class="list-inline">
			<c:if test="${empty user }">
				<li><a href="login.jsp">登入</a></li>
				<li><a href="register.jsp">註冊</a></li>
			</c:if>
			<c:if test="${!empty user }">
				<span>歡迎您,${user.username } </span>
			</c:if>
			
			
			<li><a href="cart.jsp">購物車</a></li>
			<li><a href="${pageContext.request.contextPath }/product?method=myOrder">我的訂單</a></li>
		</ol>
	</div>
</div>

<!-- 導航條 -->
<div class="container-fluid">
	<nav class="navbar navbar-inverse">
		<div class="container-fluid">
			<!-- Brand and toggle get grouped for better mobile display -->
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
					<span class="sr-only">Toggle navigation</span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">首頁</a>
			</div>
			<!-- 動態獲取商品分類ajax -->
			<script type="text/javascript">
				$(function(){
					$.post(
						"${pageContext.request.contextPath}/product?method=categoryList",
						function(data){
							//[{"cid":"xxx","cname":"xxx"},{},{},{},{}]
							var content ="";
							for (var i = 0; i < data.length; i++) {
								//content+="<li class='active'><a href='#'>"+data[i].cname+"<span class='sr-only'>(current)</span></a></li>";
								content+="<li><a href='${pageContext.request.contextPath}/product?method=productListByCid&cid="+data[i].cid+"'>"+data[i].cname+"<span class='sr-only'>(current)</span></a></li>";
							}
							$("#categoryUl").html(content);
						},
						"json"
					);
				});
			</script>
			<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
				<ul class="nav navbar-nav" id="categoryUl">
					<!-- <li class="active"><a href="product_list.htm">手機數碼<span class="sr-only">(current)</span></a></li>
					<li><a href="#">電腦辦公</a></li> -->
				</ul>
				
				<form class="navbar-form navbar-right" role="search">
					<div class="form-group">
						<input type="text" class="form-control" placeholder="Search">
					</div>
					<button type="submit" class="btn btn-default">Submit</button>
				</form>
			</div>
		</div>
	</nav>
</div>

ProductServlet
package com.itheima.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
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 org.apache.commons.beanutils.BeanUtils;

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 com.itheima.utils.PaymentUtil;

import redis.clients.jedis.Jedis;

public class ProductServlet extends BaseServlet {
	
	//顯示使用者的訂單列表
	public void myOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		//檢查使用者是否已經登陸
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user==null) {
			//重定向到登陸頁面
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		//1.查詢該使用者下的所有訂單集合,此時order物件的資料還沒封裝好,沒有orderItem集合
		ProductService service = new ProductService();
		List<Order> orderList = service.findAllOrder(user.getUid());
		//2.遍歷orders物件,多表查詢orderItem,product表
		if(orderList!=null) {
			for(Order order:orderList) {
				//3.根據oid, 查詢orderItems表,與有關聯的product表
				//獲取每個訂單的oid
				String oid = order.getOid();
				List<Map<String,Object>> mapList = service.findOrderItemsByOid(oid);
				//4.把mapList轉換為List<OrderItem> OrderItems 
				for(Map<String,Object> map:mapList) {
					try {
						//從map中抽取piame paname shop_price封裝到product中
						Product product = new Product();
						BeanUtils.populate(product, map);
						//從map中抽取count subtotal封裝到orderItem裡
						OrderItem item = new OrderItem();
						//item.setCount(Integer.parseInt(map.get("count").toString()));
						BeanUtils.populate(item, map);
						//將product封裝到orderitem中
						item.setProduct(product);
						//把orderItem物件封裝到order物件的集合裡
						order.getOrderItems().add(item);
					} catch (IllegalAccessException | InvocationTargetException e) {
						e.printStackTrace();
					}
					
				}
			}
		}
		//到目前為止,order物件封裝完畢
		//把orderList轉發到訂單顯示頁面order_list.jsp
		request.setAttribute("orderList", orderList);
		request.getRequestDispatcher("/order_list.jsp").forward(request, response);
	}

	// 確定訂單---更新收貨人的資訊與線上支付功能
	public void confirmOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.更新收貨人資訊
		// 獲取表單資料,用order封裝資料()
		Map<String, String[]> parameterMap = request.getParameterMap();
		Order order = new Order();
		try {
			BeanUtils.populate(order, parameterMap);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		// 傳遞到service層修改資料庫收貨人資訊
		ProductService service = new ProductService();
		service.updateOrderAdd(order);

		// 2.線上支付
		//第三方平臺提供的程式碼,按照自己工程修改oid 與總計
		// 獲得 支付必須基本資料
		String orderid = request.getParameter("oid");
		//支付的金額,要從記憶體獲取,不要在頁面獲取(不安全)
		String money = order.getTotal()+"";
		
		// 銀行
		String pd_FrpId = request.getParameter("pd_FrpId");

		// 發給支付公司需要哪些資料
		String p0_Cmd = "Buy";
		String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId");
		String p2_Order = orderid;
		String p3_Amt = money;
		String p4_Cur = "CNY";
		String p5_Pid = "";
		String p6_Pcat = "";
		String p7_Pdesc = "";
		// 支付成功回撥地址 ---- 第三方支付公司會訪問、使用者訪問
		// 第三方支付可以訪問網址
		String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("callback");
		String p9_SAF = "";
		String pa_MP = "";
		String pr_NeedResponse = "1";
		// 加密hmac 需要金鑰
		String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue");
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc,
				p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);

		String url = "https://www.yeepay.com/app-merchant-proxy/node?pd_FrpId=" + pd_FrpId + "&p0_Cmd=" + p0_Cmd
				+ "&p1_MerId=" + p1_MerId + "&p2_Order=" + p2_Order + "&p3_Amt=" + p3_Amt + "&p4_Cur=" + p4_Cur
				+ "&p5_Pid=" + p5_Pid + "&p6_Pcat=" + p6_Pcat + "&p7_Pdesc=" + p7_Pdesc + "&p8_Url=" + p8_Url
				+ "&p9_SAF=" + p9_SAF + "&pa_MP=" + pa_MP + "&pr_NeedResponse=" + pr_NeedResponse + "&hmac=" + hmac;

		// 重定向到第三方支付平臺
		response.sendRedirect(url);

	}

	// 提交訂單
	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 java.util.Map;

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();
			}
		}
	}

	//更新收貨人資訊
	public void updateOrderAdd(Order order) {
		ProductDao dao = new ProductDao();
		try {
			dao.updateOrderAdd(order);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	//付款成功,修改付款狀態
	public void updateState(String r6_Order) {
		ProductDao dao =new ProductDao();
		try {
			dao.updateState(r6_Order);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	//查詢使用者的所有訂單
	public List<Order> findAllOrder(String uid) {
		ProductDao dao = new ProductDao();
		List<Order> orders =null;
		try {
			orders = dao.findAllOrder(uid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orders;
	}

	//根據oid, 查詢orderItems表,與有關聯的product表
	public List<Map<String, Object>> findOrderItemsByOid(String oid) {
		ProductDao dao = new ProductDao();
		List<Map<String, Object>> mapList = null;
		try {
			mapList = dao.findOrderItemsByOid(oid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return mapList;
	}

}
ProductDao
package com.itheima.dao;

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

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.MapListHandler;
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());
		}
	}

	//更新訂單收貨人資訊
	public void updateOrderAdd(Order order) throws SQLException {
		QueryRunner runner =new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "update orders set address=?,name=?,telephone=? where oid=?";
		runner.update(sql, order.getAddress(),order.getName(),order.getTelephone(),order.getOid());
	}

	//付款成功,修改付款狀態
	public void updateState(String r6_Order) throws SQLException {
		QueryRunner runner =new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "update orders set state=? where oid=?";
		runner.update(sql, 1,r6_Order);
	}

	//查詢使用者的所有訂單
	public List<Order> findAllOrder(String uid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from orders where uid=?";
		List<Order> orders = runner.query(sql, new BeanListHandler<Order>(Order.class), uid);
		return orders;
	}

	//根據oid, 查詢orderItems表,與有關聯的product表
	public List<Map<String, Object>> findOrderItemsByOid(String oid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = 
		"select i.count,i.subtotal,p.pimage,p.pname,p.shop_price from orderitem i,product p where i.pid=p.pid and oid=? ";
		List<Map<String, Object>> query = runner.query(sql, new MapListHandler(), oid);
		return query;
	}

}
order_list.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">
					<!-- 遍歷orderList -->
					<c:forEach items="${orderList }" var="order">
						<tbody>
							<tr class="success">
								<th colspan="5">訂單編號:${order.oid }      
								${order.state==0?"<a href='javascript:;'>未付款</a>":"已付款" }     
								${order.total }</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>
					</c:forEach>
				</table>
			</div>
		</div>
		<div style="text-align: center;">
			<ul class="pagination">
				<li class="disabled"><a href="#" aria-label="Previous"><span
						aria-hidden="true">«</span></a></li>
				<li class="active"><a href="#">1</a></li>
				<li><a href="#">2</a></li>
				<li><a href="#">3</a></li>
				<li><a href="#">4</a></li>
				<li><a href="#">5</a></li>
				<li><a href="#">6</a></li>
				<li><a href="#">7</a></li>
				<li><a href="#">8</a></li>
				<li><a href="#">9</a></li>
				<li><a href="#" aria-label="Next"> <span aria-hidden="true">»</span>
				</a></li>
			</ul>
		</div>
	</div>

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

</html>