码迷,mamicode.com
首页 > 其他好文 > 详细

8.修改 按条件查询商品 分页

时间:2018-02-19 00:38:03      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:选择   记录   ebean   用户   添加   tca   持久层   pat   tostring   

修改商品的原理图

技术分享图片

 

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.修改 按条件查询商品 分页

标签:选择   记录   ebean   用户   添加   tca   持久层   pat   tostring   

原文地址:https://www.cnblogs.com/syj1993/p/8453022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!