Java Web 网络商城案例演示十一(商品分页)
基础的分页操作
web阶段项目中:CRUD,ajax,分页,下载,上传
新建一个动态的web工程
分析SQL语句的实现
– 约定每页能够显示5条数据
SELECT * FROM product LIMIT 0,5;
SELECT * FROM product LIMIT 5,5;
SELECT * FROM product LIMIT 10,5;
SELECT * FROM product LIMIT 15,5;
第几页数(当前页) | 起始值 | 每一页数据的大小 |
---|---|---|
1 | 0 | 5 |
2 | 5 | 5 |
3 | 10 | 5 |
4 | 15 | 5 |
结论:
1、(当前页减去1)乘以(每页的数量)=起始值
2、结论要想实现分页,向服务端发起请求的时候,必须传递当前页
原理分析:
步骤实现:
1、new DynamicWebProject (TestPageination)
2、导入jar包,工具类,配置文件(修改参数)创建相关的程序servlet,service ,dao ,product
在utils下面创建Product 类
public class Product {
private String pid;//商品编号
private String pname;//商品的名称
private double market_price;//商品市场价格
private double shop_price;//商品的商场价格
private String pimage;//商品的图片路径
private Date pdate;//商品的上架的日期
private String is_hot;//商品是否热门
private String pdesc;//商品描述
private int pflag;//商品的是否在货架上 0 在货架上 1 下架
private String cid;//商品所在分类的id
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getMarket_price() {
return market_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public double getShop_price() {
return shop_price;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public Date getPdate() {
return pdate;
}
public void setPdate(Date pdate) {
this.pdate = pdate;
}
public String getIs_hot() {
return is_hot;
}
public void setIs_hot(String is_hot) {
this.is_hot = is_hot;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public int getPflag() {
return pflag;
}
public void setPflag(int pflag) {
this.pflag = pflag;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public Product() {
// TODO Auto-generated constructor stub
}
public Product(String pid, String pname, double market_price, double shop_price, String pimage, Date pdate,
String is_hot, String pdesc, int pflag, String cid) {
super();
this.pid = pid;
this.pname = pname;
this.market_price = market_price;
this.shop_price = shop_price;
this.pimage = pimage;
this.pdate = pdate;
this.is_hot = is_hot;
this.pdesc = pdesc;
this.pflag = pflag;
this.cid = cid;
}
@Override
public String toString() {
return "Product [pid=" + pid + ", pname=" + pname + ", market_price=" + market_price + ", shop_price="
+ shop_price + ", pimage=" + pimage + ", pdate=" + pdate + ", is_hot=" + is_hot + ", pdesc=" + pdesc
+ ", pflag=" + pflag + ", cid=" + cid + "]";
}
}
c3p0链接数据库
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/store_07</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
<user-overrides user="test-user">
<property name="maxPoolSize">10</property>
<property name="minPoolSize">1</property>
<property name="maxStatements">0</property>
</user-overrides>
</default-config>
<!-- 命名的配置 -->
<named-config name="itzheng">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/store_07</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
/**
* Servlet implementation class ProductServlet
*/
public class ProductServlet extends HttpServlet {
/**
* @see HttpServlet#HttpServlet()
*/
public ProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收当前页
String num=request.getParameter("num");
int curNum=Integer.parseInt(num);
System.out.println(curNum);
ProductService ProductService=new ProductService();
//调用业务层查询当前页功能,返回PageModel对象(1_当前页数据2_分页参数)
PageModel pm=null;
try {
pm = ProductService.findProducts(curNum);
} catch (Exception e) {
e.printStackTrace();
}
//将PageModel对象放入request
request.setAttribute("page", pm);
//request.getRequestDispatcher("/product_list.jsp").forward(request, response);
request.getRequestDispatcher("/product_list2.jsp").forward(request, response);
}
}
public class ProductService {
public PageModel findProducts(int curNum) throws SQLException{
//1_创建PageModel对象 目的:计算分页参数
ProductDao ProductDao=new ProductDao();
int totalRecords=ProductDao.findToralRecords();
PageModel pm=new PageModel(curNum,5,totalRecords);//传入要点击的页数,和每页的页数,和对应总信息的条数
//2_关联数据 select * from product limit ? , ?
List list=ProductDao.findProducts(pm.getStartIndex(),pm.getPageSize());
pm.setList(list);
//3_关联url
pm.setUrl("ProductServlet");
return pm;
}
}
public class ProductDao {
//统计表中有多少条数据
public int findToralRecords() throws SQLException {
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
Long num=(Long)qr.query("select count(*) from product",new ScalarHandler());
return num.intValue();
}
public List findProducts(int startIndex, int pageSize) throws SQLException {
String sql="select * from product limit ? ,? ";
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
return qr.query(sql, new BeanListHandler<Product>(Product.class),startIndex,pageSize);
}
}
product_list.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td>商品名称</td>
<td>市场价格</td>
<td>商场价格</td>
<td>商品图片</td>
</tr>
<c:if test="${empty page.list }">
<tr><td colspan="4">暂无数据</td></tr>
</c:if>
<c:if test="${not empty page.list }">
<c:forEach items="${page.list}" var="p">
<tr>
<td>${p.pname}</td>
<td>${p.market_price}</td>
<td>${p.shop_price}</td>
<td>
<img src="${pageContext.request.contextPath}/${p.pimage}" width="50px"/>
</td>
</tr>
</c:forEach>
</c:if>
</table>
<%--分页显示的开始 --%>
<div style="text-align:center">
共${page.totalPageNum}页/第${page.currentPageNum}页
<a href="${pageContext.request.contextPath}/ProductServlet?num=1">首页</a>
<c:if test="${page.currentPageNum != 1}">
<a href="${pageContext.request.contextPath}/ProductServlet?num=${page.prePageNum}">上一页</a>
</c:if>
<%-- 获取开始结束页码
${page} *.getAttribute("page"); 获取到pageModel对象
${page.startPage} 调用PageModel对象getStartPage()方法
--%>
<c:forEach begin="${page.startPage}" end="${page.endPage}" var="pagenum">
<c:if test="${page.currentPageNum==pagenum}">
${pagenum}
</c:if>
<c:if test="${page.currentPageNum!=pagenum}">
<a href="${pageContext.request.contextPath}/ProductServlet?num=${pagenum}">${pagenum}</a>
</c:if>
</c:forEach>
<c:if test="${page.currentPageNum != page.totalPageNum}">
<a href="${pageContext.request.contextPath}/ProductServlet?num=${page.nextPageNum}">下一页</a>
</c:if>
<a href="${pageContext.request.contextPath}/ProductServlet?num=${page.totalPageNum}">末页</a>
<input type="text" id="pagenum" name="pagenum" size="1"/>
<input type="button" value="前往" onclick="jump()" />
<script type="text/javascript">
function jump(){
//通过EL获取到总共页数,赋值给JS中变量
var totalpage = ${page.totalPageNum};
//获取到用户输入的内容
var pagenum = document.getElementById("pagenum").value;
//判断输入的是一个数字
var reg =/^[1-9][0-9]*$/;
if(!reg.test(pagenum)){
//不是一个有效数字
alert("请输入符合规定的数字");
return ;
}
//paseInt(pageNum):将用户输入的内容转换为int类型数字
//判断输入的数字不能大于总页数
if(parseInt(pagenum)>parseInt(totalpage)){
//超过了总页数
alert("不能大于总页数");
return;
}
//转向分页显示的Servlet
window.location.href="${pageContext.request.contextPath}/ProductServlet?num="+pagenum;
}
</script>
</div>
<%--分页显示的结束--%>
</body>
</html>
product_list2.jsp