1. 程式人生 > >8.修改 按條件查詢商品 分頁

8.修改 按條件查詢商品 分頁

edi spl stat htm != pic check ren lib

修改商品的原理圖

技術分享圖片

jsp頁面

edit.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<HTML>
<HEAD>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK href="${pageContext.request.contextPath}/admin/css/Style.css"
	type="text/css" rel="stylesheet">
<script language="javascript"
	src="${pageContext.request.contextPath}/admin/js/public.js"></script>
<script language="javascript"
	src="${pageContext.request.contextPath}/admin/js/check.js"></script>

</HEAD>
<body>

	<!-- 
		上傳文件
		enctype="multipart/form-data"
		修改語句:update products set xxx xxx xxx where pid=?   
		偷偷的傳
	 -->
	<form id="userAction_save_do" name="Form1" action="${pageContext.request.contextPath }/product" method="post" >
	
		<!-- post提交方法添加一個隱藏域 -->
		<input type="hidden" name="method" value="update"/>
		<input type="hidden" name="pid" value="${product.pid }"/>
		
		<table cellSpacing="1" cellPadding="5" width="100%" align="center"
			bgColor="#eeeeee" style="border: 1px solid #8ba7e3" border="0">
			<tr>
				<td class="ta_01" align="center" bgColor="#afd1f3" colSpan="4"
					height="26"><strong><STRONG>編輯商品</STRONG> </strong></td>
			</tr>


			<tr>
				<td align="center" bgColor="#f5fafe" class="ta_01">商品名稱:</td>
				<td class="ta_01" bgColor="#ffffff">
					<input type="text" name="pname" class="bg" value="${product.pname }" /></td>
				<td align="center" bgColor="#f5fafe" class="ta_01">商品價格:</td>
				<td class="ta_01" bgColor="#ffffff">
					<input type="text" name="price" class="bg" value="${product.price }" /></td>
			</tr>
			<tr>
				<td align="center" bgColor="#f5fafe" class="ta_01">商品數量:</td>
				<td class="ta_01" bgColor="#ffffff">
					<input type="text" name="pnum" class="bg" value="${product.pnum }" /></td>
				<td align="center" bgColor="#f5fafe" class="ta_01">商品類別:</td>
				<td class="ta_01" bgColor="#ffffff">
					
					<%-- 判斷類別
					<c:if test="${product.category eq ‘計算機‘ }">selected</c:if> --%>
					
					<select name="category" id="category">
						<option value="">--選擇商品類加--</option>
						<option value="文學" <c:if test="${product.category eq ‘文學‘ }">selected</c:if>>文學</option>
						<option value="生活" <c:if test="${product.category eq ‘生活‘ }">selected</c:if>>生活</option>
						<option value="計算機" <c:if test="${product.category eq ‘計算機‘ }">selected</c:if>>計算機</option>
						<option value="外語" <c:if test="${product.category eq ‘外語‘ }">selected</c:if>>外語</option>
						<option value="經營" <c:if test="${product.category eq ‘經營‘ }">selected</c:if>>經營</option>
						<option value="勵誌" <c:if test="${product.category eq ‘勵誌‘ }">selected</c:if>>勵誌</option>
						<option value="社科" <c:if test="${product.category eq ‘社科‘ }">selected</c:if>>社科</option>
						<option value="學術" <c:if test="${product.category eq ‘學術‘ }">selected</c:if>>學術</option>
						<option value="少兒" <c:if test="${product.category eq ‘少兒‘ }">selected</c:if>>少兒</option>
						<option value="藝術" <c:if test="${product.category eq ‘藝術‘ }">selected</c:if>>藝術</option>
						<option value="原版" <c:if test="${product.category eq ‘原版‘ }">selected</c:if>>原版</option>
						<option value="科技" <c:if test="${product.category eq ‘科技‘ }">selected</c:if>>科技</option>
						<option value="考試" <c:if test="${product.category eq ‘考試‘ }">selected</c:if>>考試</option>
						<option value="生活百科" <c:if test="${product.category eq ‘生活百科‘ }">selected</c:if>>生活百科</option>
				</select></td>
			</tr>


			<tr>
				<td align="center" bgColor="#f5fafe" class="ta_01">商品圖片:</td>
				<td class="ta_01" bgColor="#ffffff" colSpan="3">
					<input type="file" name="upload" size="30" value="" /></td>
			</tr>
			<TR>
				<TD class="ta_01" align="center" bgColor="#f5fafe">商品描述:</TD>
				<TD class="ta_01" bgColor="#ffffff" colSpan="3">
					<textarea name="description" cols="30" rows="3" style="WIDTH: 96%">${product.description}</textarea>
				</TD>
			</TR>
			<TR>
				<td align="center" colSpan="4" class="sep1"><img
					src="${pageContext.request.contextPath}/admin/images/shim.gif">
				</td>
			</TR>


			<tr>
				<td class="ta_01" style="WIDTH: 100%" align="center" bgColor="#f5fafe" colSpan="4">
					<!-- 提交 -->
					<input type="submit"class="button_ok" value="確定"> 
					<FONT face="宋體">       </FONT>

					<!-- 重置 -->
					<input type="reset" value="重置" class="button_cancel"> <FONT
					face="宋體">       </FONT> 
					
					<!-- 返回 -->
					<INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回" />
					<span id="Label1"> </span>
				</td>
			</tr>
		</table>
	</form>




</body>
</HTML>


list.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<HTML>
<HEAD>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="${pageContext.request.contextPath}/admin/css/Style.css"
	rel="stylesheet" type="text/css" />
<script language="javascript"
	src="${pageContext.request.contextPath}/admin/js/public.js"></script>
<script type="text/javascript">
	//點擊添加的按鈕,跳轉到添加商品的頁面
	function addProduct() {
		//相當於超鏈接
		window.location.href = "${pageContext.request.contextPath}/admin/products/add.jsp";
	}
</script>
</HEAD>
<body>
	<br>
	<!-- 
		按條件查詢
		按條件查詢
		按條件查詢
		按條件查詢
		按條件查詢
	 -->
	<form id="Form1" name="Form1" action="${pageContext.request.contextPath}/product" method="post">
	
		<input type="hidden" name="method" value="findByWhere"/>
	
		<table cellSpacing="1" cellPadding="0" width="100%" align="center" bgColor="#f5fafe" border="0">
			<TBODY>
				<tr>
					<td class="ta_01" align="center" bgColor="#afd1f3">
						<strong>查詢 條 件</strong>
					</td>
				</tr>
				<tr>
					<td>
						<table cellpadding="0" cellspacing="0" border="0" width="100%">
							<tr>
								<td height="22" align="center" bgColor="#f5fafe" class="ta_01">
									商品編號:
								</td>
								<td class="ta_01" bgColor="#ffffff">
									<input type="text" name="pid" size="15"  id="Form1_userName" class="bg" />
								</td>
								
								<td height="22" align="center" bgColor="#f5fafe" class="ta_01">
									類別:
								</td>
								<td class="ta_01" bgColor="#ffffff">
									<select name="category" id="category">
										<option value="" selected="selected">--選擇商品類加--</option>
										<option value="文學">文學</option>
										<option value="生活">生活</option>
										<option value="計算機">計算機</option>
										<option value="外語">外語</option>
										<option value="經營">經營</option>
										<option value="勵誌">勵誌</option>
										<option value="社科">社科</option>
										<option value="學術">學術</option>
										<option value="少兒">少兒</option>
										<option value="藝術">藝術</option>
										<option value="原版">原版</option>
										<option value="科技">科技</option>
										<option value="考試">考試</option>
										<option value="生活百科">生活百科</option>
									</select>
								</td>
							</tr>

							<tr>
								<td height="22" align="center" bgColor="#f5fafe" class="ta_01">
									商品名稱:
								</td>
								<td class="ta_01" bgColor="#ffffff">
									<input type="text" name="pname" size="15" id="Form1_userName" class="bg" />
								</td>
								
								<td height="22" align="center" bgColor="#f5fafe" class="ta_01">價格區間(元):</td>
								<td class="ta_01" bgColor="#ffffff">
									<input type="text" name="minprice" size="10" />- 
									<input type="text" name="maxprice" size="10" />
								</td>
							</tr>

							<tr>
								<td width="100" height="22" align="center" bgColor="#f5fafe"class="ta_01"></td>
								<td class="ta_01" bgColor="#ffffff">
									<font face="宋體" color="red">  </font>
								</td>
								<td align="right" bgColor="#ffffff" class="ta_01"><br><br></td>
									
								<td align="right" bgColor="#ffffff" class="ta_01">
									<button type="submit" id="search" name="search" value="查詢" class="button_view">
										查詢
									</button>       
									<input type="reset" name="reset" value="重置" class="button_view" />
								</td>
							</tr>
						</table>
					</td>
				</tr>
				
				
				<tr>
					<td class="ta_01" align="center" bgColor="#afd1f3"><strong>商品列表</strong>
					</TD>
				</tr>
				<tr>
					<td class="ta_01" align="right">
						<!-- 
							添加的按鈕
							添加的按鈕
							添加的按鈕
							添加的按鈕
							添加的按鈕
							添加的按鈕
							添加的按鈕
							添加的按鈕
						 -->
						<button type="button" id="add" name="add" value="添加;"
							class="button_add" onclick="addProduct()">添加
						</button>
					</td>
				</tr>
				<tr>
					<td class="ta_01" align="center" bgColor="#f5fafe">
						<table cellspacing="0" cellpadding="1" rules="all"
							bordercolor="gray" border="1" id="DataGrid1"
							style="BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; WIDTH: 100%; WORD-BREAK: break-all; BORDER-BOTTOM: gray 1px solid; BORDER-COLLAPSE: collapse; BACKGROUND-COLOR: #f5fafe; WORD-WRAP: break-word">
							<tr
								style="FONT-WEIGHT: bold; FONT-SIZE: 12pt; HEIGHT: 25px; BACKGROUND-COLOR: #afd1f3">
								<td align="center" width="24%">序號</td>
								<td align="center" width="18%">商品名稱</td>
								<td align="center" width="9%">商品價格</td>
								<td align="center" width="9%">商品數量</td>
								<td width="8%" align="center">商品類別</td>
								<td width="8%" align="center">編輯</td>

								<td width="8%" align="center">刪除</td>
							</tr>

							<!-- for標簽想象增強for循環 for(數據類型 變量:要遍歷的集合) -->
							<c:forEach var="p" items="${pList }" varStatus="vs"> <!-- varStatus用於叠代數據,從1開始 -->
								<tr onmouseover="this.style.backgroundColor = ‘white‘"
									onmouseout="this.style.backgroundColor = ‘#F5FAFE‘;">
									<td style="CURSOR: hand; HEIGHT: 22px" align="center"
										width="23">${vs.count }</td>
									<td style="CURSOR: hand; HEIGHT: 22px" align="center"
										width="18%">${p.pname }</td>
									<td style="CURSOR: hand; HEIGHT: 22px" align="center"
										width="8%">${p.price }</td>
									<td style="CURSOR: hand; HEIGHT: 22px" align="center"
										width="8%">${p.pnum }</td>
									<td style="CURSOR: hand; HEIGHT: 22px" align="center">
										${p.category }</td>
										
									<!-- 
										編輯修改
										編輯修改
										編輯修改
										編輯修改
										編輯修改
										編輯修改
									 -->
									<td align="center" style="HEIGHT: 22px" width="7%">
										<a href="${pageContext.request.contextPath }/product?method=initUpdate&pid=${p.pid}">
											<img 
											src="${pageContext.request.contextPath}/admin/images/i_edit.gif"
											border="0" style="CURSOR: hand"> </a>
									</td>

									<td align="center" style="HEIGHT: 22px" width="7%"><a
										href="#">
											<img
											src="${pageContext.request.contextPath}/admin/images/i_del.gif"
											width="16" height="16" border="0" style="CURSOR: hand">
									</a>
									</td>
								</tr>
							</c:forEach>
						</table>
					</td>
				</tr>
			</TBODY>
		</table>
	</form>
</body>
</HTML>

三層架構

/**
 * 商品的控制器
 * @author mjl
 *
 */
public class ProductServlet extends BaseServlet {
	
	/**
	 * 添加商品
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void addProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 1.接收數據
		 * 2.封裝數據
		 * 3.處理數據
		 * 4.顯示數據
		 */

		//接收數據
		Map<String,String[]> map=request.getParameterMap();
		Product p=new Product();
		try {
			//封裝數據
			BeanUtils.populate(p, map);
			System.out.println(p);
			
			//處理數據
			ProductService ps=new ProductService();
			//保存數據
			ps.save(p);
			
			//如果添加成功,重定向到findAll  
			response.sendRedirect(request.getContextPath()+"/product?method=findAll");
		} catch (Exception e) {
			e.printStackTrace();
			//捕獲異常
			request.setAttribute("msg", e.getMessage());
			request.getRequestDispatcher("/admin/products/add.jsp").forward(request, response);
		}
	}
	
	/**
	 * 查詢所有的商品
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		/**
		 * 1.接收數據
		 * 2.封裝數據
		 * 3.處理數據
		 * 4.顯示數據
		 */
		
		//沒有參數,也不用封裝
		ProductService ps=new ProductService();
		//查詢所有的商品的信息
		List<Product> pList=ps.findAll();
		//存入到request域對象中
		request.setAttribute("pList", pList);
		request.getRequestDispatcher("/admin/products/list.jsp").forward(request, response);
		
		/*前後兩個頁面 有數據傳遞 用請求轉發,沒有則用重定向。
		比如servlet查詢了數據需要在頁面顯示,就用請求轉發。
		比如servlet做了update操作跳轉到其他頁面,就用重定向。*/
	}
	
	/**
	 * 初始化的修改頁面
	 * 用於點擊編輯按鈕跳轉到編輯頁面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	
	public void initUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 通過主鍵去查詢該條記錄
		 */
		String pid=request.getParameter("pid");
		ProductService ps=new ProductService();
		Product p=ps.findById(pid);
		
		//存入到request域
		/**
		 * 服務器端域對象 域對象可以共享數據
		 * servletContext  服務器啟動,ServletContext創建了,服務器關閉的時候,銷毀!與天地同壽!!被所有的資源共享。
		 * HttpSession     代表一次會話!打開瀏覽器開始,關閉瀏覽器結束。發送多次請求,得到多次響應。保存每個人相關的信息。
		 * request		        代表一次請求。只能發送一次,發送完畢就銷毀。保存一些提示的信息,或者要顯示的數據的。
		 */
		request.setAttribute("product", p);
		request.getRequestDispatcher("/admin/products/edit.jsp").forward(request, response);
	}
	
	
	/**
	 * 修改商品
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取數據
		Map<String,String[]> map=request.getParameterMap();
		Product product=new Product();
		try {
			BeanUtils.populate(product, map);
			ProductService ps=new ProductService();
			ps.update(product);
			
			//跳轉到頁面
			//如果修改成功,重定向到findAll  
			response.sendRedirect(request.getContextPath()+"/product?method=findAll");
		} catch (Exception e) {
			e.printStackTrace();
		} 	
	}
	
	
	/**
	 * 按條件查詢所有的商品
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void findByWhere(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收請求的參數
		String pid=request.getParameter("pid");
		String category=request.getParameter("category");
		String pname=request.getParameter("pname");
		String minprice=request.getParameter("minprice");
		String maxprice=request.getParameter("maxprice");
		
		//調用持久層
		ProductService ps=new ProductService();

		List<Product> pList=ps.findByWhere(pid,category,pname,minprice,maxprice);
		
		request.setAttribute("pList", pList);
		request.getRequestDispatcher("/admin/products/list.jsp").forward(request, response);
	}
}


/**
 * 商品業務層
 * @author mjl
 *
 */
public class ProductService {
	
	/**
	 * 保存商品
	 * @param p
	 * @throws SQLException 
	 * @throws MyException 
	 */
	public void save(Product p) throws SQLException, MyException{
		//自己維護主鍵
		p.setPid(MyUUIDUtils.getUUID());
		
		//先設置imgurl屬性值為Null
		p.setImgUrl(null);
		
		//調用持久層,保存數據
		ProductDao dao=new ProductDao();
		dao.save(p);
	}

	/**
	 * 查詢所有的商品
	 * @return
	 */
	public List<Product> findAll() {
		
		ProductDao dao=new ProductDao();
		return dao.findAll();
	}

	/**
	 * 通過主鍵查詢該條記錄
	 * @param pid
	 * @return
	 */
	public Product findById(String pid) {
		
		ProductDao dao=new ProductDao();
		return dao.findById(pid);
	}

	/**
	 * 修改商品
	 * @param product
	 */
	public void update(Product product) {
		
		ProductDao dao=new ProductDao();
		dao.update(product);
	}

	/**
	 * 按條件查詢
	 * @param pid
	 * @param category
	 * @param pname
	 * @param minprice
	 * @param maxprice
	 * @return
	 */
	public List<Product> findByWhere(String pid, String category, String pname, String minprice, String maxprice) {
		
		ProductDao dao=new ProductDao();
		return dao.findByWhere(pid,category,pname,minprice,maxprice);
	}

	public List<Product> findByCondition(String pid, String category, String pname, String minprice, String maxprice) {
		ProductDao dao=new ProductDao();
		return dao.findByCondition(pid,category,pname,minprice,maxprice); 
	}
}


/**
 * 商品的持久層
 * @author mjl
 *
 */
public class ProductDao {

	public void save(Product p) throws SQLException, MyException{
		//使用DBUtils工具類
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		//編寫sql語句
		String sql="insert into products values(?,?,?,?,?,?,?)";
		Object [] params={p.getPid(),p.getPname(),p.getPrice(),p.getCategory(),p.getPnum(),p.getImgUrl(),p.getDescription()};
		//執行sql語句,如果成功,返回1
		int count=runner.update(sql, params);
		if(count!=1){
			throw new MyException("親,添加商品錯誤");
		}
	}

	public List<Product> findAll() {
		
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		try {
			return runner.query("select * from products", new BeanListHandler<Product>(Product.class));
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查詢所有的商品錯誤了!");
		}
	}

	public Product findById(String pid) {

		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		try {
			Product p=runner.query("select * from products where pid=?", new BeanHandler<Product>(Product.class),pid);
			return p;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查詢該條記錄錯誤了!");
		}
	}

	public void update(Product p) {
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		String sql="update products set pname=?,price=?,category=?,pnum=?,imgurl=?,description=? where pid=?";
		Object [] params={p.getPname(),p.getPrice(),p.getCategory(),p.getPnum(),p.getImgUrl(),p.getDescription(),p.getPid()};
		try {
			runner.update(sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public List<Product> findByWhere(String pid, String category, String pname, String minprice, String maxprice) {
		
		//創建集合,用來存儲參數
		List<Object> list=new ArrayList<Object>();
		
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		
		//拼接sql語句
		StringBuffer sb=new StringBuffer("select * from products where 1=1 ");
		
		//判斷參數是否為空,如果不為空,說明用戶輸入了這些值,如果為空,說明沒有輸入
		if(pid!=null && !pid.trim().isEmpty()){ //trim()去掉空格
			//拼接sql語句
			sb.append(" and pid like ? "); //like模糊查詢
			list.add("%"+pid+"%");
		}
		
		if(category!=null && !category.trim().isEmpty()){ //trim()去掉空格
			//拼接sql語句
			sb.append(" and category = ? "); 
			list.add(category);
		}
		
		if(pname!=null && !pname.trim().isEmpty()){ //trim()去掉空格
			//拼接sql語句
			sb.append(" and pname = ? "); 
			list.add(pname);
		}
		
		if(minprice!=null && !minprice.trim().isEmpty()){ //trim()去掉空格
			//拼接sql語句
			sb.append(" and price > ? "); 
		}
		
		if(maxprice!=null && !maxprice.trim().isEmpty()){ //trim()去掉空格
			//拼接sql語句
			sb.append(" and price < ? "); 
			list.add(maxprice);
		}
		
		//執行
		try {
			return runner.query(sb.toString(), new BeanListHandler<Product>(Product.class),list.toArray());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
	}

	

	public List<Product> findByCondition(String pid, String category, String pname, String minprice, String maxprice) {
		
		
		StringBuffer sb=new StringBuffer();
		sb.append("select * from products where 1=1 ");
		
		List<Object> list=new ArrayList();
		
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		
		
		if(pid!=null && !pid.trim().isEmpty()){
			sb.append(" and pid like ? ");
			list.add("%"+pid+"%");
		}
		
		
		if(category!=null && !category.trim().isEmpty()){
			sb.append(" and category = ? ");
			list.add(category);
		}
		
		if(pname!=null && !pname.trim().isEmpty()){
			sb.append(" and pname = ? ");
			list.add(pname);
		}
		if(minprice!=null && !minprice.trim().isEmpty()){
			sb.append(" and price > ? ");
			list.add(minprice);
		}
		if(maxprice!=null && !maxprice.trim().isEmpty()){
			sb.append(" and price< ? ");
			list.add(maxprice);
		}
		
		try {
			return runner.query(sb.toString(), new BeanListHandler<Product>(Product.class),list.toArray());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

}

  

分頁的實現

技術分享圖片

jsp頁面中,點擊全部商品跳轉servlet

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/my.js">
	
</script>
<script type="text/javascript">

</script>

<div id="divmenu">
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=文學">文學</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活">生活</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=計算機">計算機</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=外語">外語</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=經營">經管</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=勵誌">勵誌</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=社科">社科</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=學術">學術</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=少兒">少兒</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=藝術">藝術</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=原版">原版</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=科技">科技</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=考試">考試</a>
	<a
		href="${pageContext.request.contextPath}/showProductByPage?category=生活百科">生活百科</a>
	<a href="${pageContext.request.contextPath}/product?method=findByPage" style="color:#FFFF00">全部商品目錄</a>
</div>
<div id="divsearch">
	<form action="${pageContext.request.contextPath}/findProductBySearch"
		method="post">
		<table width="100%" border="0" cellspacing="0">
			<tr>
				<td style="text-align:right; padding-right:220px">
				Search <input
					type="text" name="name" class="inputtable" onkeyup="searchName();"
					id="name" /> 
					<input type="image" src="images/serchbutton.gif"
					border="0" style="margin-bottom:-4px">
				</td>
			</tr>
		</table>

	</form>
</div>
<div id="content"
	style="background-color:white;width:128px; text-align:left;margin-left:945px;color:black;float:left;margin-top: -20px;display: none">
</div>

ProductServlet處理業務邏輯

/**
	 * 分頁查詢
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 1.解決當前頁的問題
		 *  以後用戶在客戶端給我傳參數,如果參數為null,說明是第一頁,如果不為空,傳的是幾頁就是幾頁
		 * 2.每一頁顯示的條數的問題
		 */
		
		//1.解決當前頁的問題
		int pageCode=getPageCode(request);
		
		//2.解決每頁顯示的記錄條數
		int pageSize=4;
		
		//調用業務層
		ProductService ps=new ProductService();
		
		//分頁的查詢
		PageBean page=ps.findByPage(pageCode,pageSize);
		
		//存入
		request.setAttribute("page", page);
		request.getRequestDispatcher("/product_list.jsp").forward(request, response);
	}
	
	
	/**
	 * 獲取當前頁
	 * @param request
	 * @return
	 */
	public int getPageCode(HttpServletRequest request){
		//獲取當前頁
		String pc=request.getParameter("pc");
		//判斷,說明pc沒有傳,說明第一次
		if(pc==null){
			return 1;
		}else{
			return Integer.parseInt(pc);
		}
	}

  

ProductService

/**
	 * 分頁的查詢
	 * @param pageCode
	 * @param pageSize
	 * @return
	 */
	public PageBean findByPage(int pageCode, int pageSize) {
		ProductDao dao=new ProductDao();
		return dao.finByPage(pageCode,pageSize);
	}

  

ProductDao

/**
	 * 分頁的查詢
	 * @param pageCode
	 * @param pageSize
	 * @return
	 */
	public PageBean finByPage(int pageCode, int pageSize) {
		//目的:創建PageBean對象,把所有的屬性數據全部搞定
		PageBean<Product> page=new PageBean();
		page.setPageCode(pageCode);
		page.setPageSize(pageSize);
		
		QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource());
		
		//設置總的記錄數
		String countSql="select count(*) from products ";
		String selSql="select * from products limit ?,?";
		
		
		try {
			//查詢總的記錄數
			long totalCount=(long) runner.query(countSql, new ScalarHandler());
			
			//設置總的記錄數
			page.setTotalCount((int)totalCount);
			
			//查詢每頁顯示的數據
			List<Product> beanList=runner.query(selSql, new BeanListHandler<Product>(Product.class),(pageCode-1)*pageSize,pageSize);
			
			//設置每頁顯示的數據
			page.setBeanList(beanList);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		return page;
	}

  

product_list.jsp頁面顯示分頁內容

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>bookStore列表</title>
<%--導入css --%>
<link rel="stylesheet" href="css/main.css" type="text/css" />
</head>

<body class="main">

	<jsp:include page="head.jsp" />
	<jsp:include page="menu_search.jsp" />

	<div id="divpagecontent">
		<table width="100%" border="0" cellspacing="0">
			<tr>

				<td>
					<div style="text-align:right; margin:5px 10px 5px 0px">
						<a href="index.jsp">首頁</a>    >    計算機    >    圖書列表
					</div>

					<table cellspacing="0" class="listcontent">
						<tr>
							<td>
								<h1>商品目錄</h1>
								<hr />
								<h1>計算機</h1>    共${page.totalCount }種商品
								<hr />
								<div style="margin-top:20px; margin-bottom:5px">
									<img src="images/productlist.gif" width="100%" height="38" />
								</div>
								<table cellspacing="0" class="booklist">
									
									
									<!-- 一頁只有四個 對象,所以遍歷4次  -->
									<tr>
										<c:forEach var="p" items="${page.beanList }">										
											<td>
												<div class="divbookpic">
													<p>
														<a href="product_info.jsp">
															<img src="bookcover/101.jpg" width="115" height="129" border="0" /> 
														</a>
													</p>
												</div>
	
												<div class="divlisttitle">
													<a href="product_info.jsp">書名:${p.pname }<br />售價:${p.price } </a>
												</div>
											</td>
										</c:forEach>
									</tr>
								</table>
								

								<div class="pagination">
									<ul>
										<c:if test="${page.pageCode>1 }">
											<li class="disablepage">
												<a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${page.pageCode-1}" >上一頁</a>
											</li>	
										</c:if>
										
										<!--也可以產生這種循環 for(int i=1;i<=10;i++){} -->
										<%--
											目的:控制begin和end的值
											邏輯:
												當總頁數<=10,說明一共不超過10頁,讓begin=1,end=總頁數
												當總頁數>10,讓begin=pageCode-5,end=pageCode+4
													頭溢出:
														如果當前頁=3,begin=3-5=-2
														如果begin<1,讓begin=1,end=10
													尾溢出:
														如果end>總頁數,讓end=總頁數,begin=總頁數-9
										 --%>
									
										<!--  編寫邏輯  判斷開始頁碼結束頁碼-->
										 <c:choose>
										 	<c:when test="${page.totalPage<=10 }">
										 		<c:set var="begin" value="1" ></c:set>
												<c:set var="end" value="${page.totalPage }"></c:set>
										 	</c:when>
										 	<c:otherwise>
										 		<c:set var="begin" value="${page.pageCode-5 }" ></c:set>
										 		<c:set var="end" value="${page.pageCode+4 }"></c:set>
										 		
										 		<!-- 判斷頭溢出 -->
										 		<c:if test="${begin<1 }">
										 			<c:set var="begin" value="1" ></c:set>
										 			<c:set var="end" value="10"></c:set>
										 		</c:if>
										 		
										 		<!-- 判斷尾溢出 -->
										 		<c:if test="${end>page.totalPage }">
										 			<c:set var="begin" value="${page.totalPage-9 }" ></c:set>
										 			<c:set var="end" value="${page.totalPage }"></c:set>
										 		</c:if>
										 	</c:otherwise>
										 </c:choose>
										 
										 
										<c:forEach var="i" begin="${begin }" end="${end }" step="1">
											<!-- 當前頁==i -->
											<c:if test="${page.pageCode==i }">
												<li class="currentpage">${i }</li>
											</c:if>
											<c:if test="${page.pageCode!=i }">
												<li><a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${i}">${i }</a>
											</c:if>
										</c:forEach>

										<c:if test="${page.pageCode<page.totalPage }">
											<li class="nextpage">
												<a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${page.pageCode+1}">下一頁</a>
											</li>
										</c:if>

									</ul>
								</div>
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</div>


	<jsp:include page="foot.jsp" />

</body>
</html>

  

8.修改 按條件查詢商品 分頁