准备工作
1.数据库和表
创建自己的数据库和表
2.创建项目
demo
3.引入jar包
4.创建包结构,导入工具类,引入配置文件
javabean:product
package com.domain;
public class Product {
private String pid;
private String pname;
private Double market_price;
private Double shop_price;
private String pimage;
private String pdate;
private String pdesc;
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 String getPdate() {
return pdate;
}
public void setPdate(String pdate) {
this.pdate = pdate;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
}
这里主要说一下模型PageModel
package com.domain;
import java.util.List;
/**
* 存放分页相关的数据
*
*/
public class PageModel {
//基本属性
private int currentPageNum;//当前页数,由用户指定 *
private int pageSize = 5 ;//每页显示的条数,固定的 *
private int totalRecords;//总记录条数,数据库查出来的 *
private int totalPageNum;//总页数,计算出来的 *
private int startIndex;//每页开始记录的索引,计算出来的 *
private int prePageNum;//上一页 *
private int nextPageNum;//下一页 *
private List list;//已经分好页的结果集,该list中只有10条记录
//扩展属性
//一共每页显示9个页码按钮
private int startPage;//开始页码
private int endPage;//结束页码
//完善属性
private String url;
//要想使用我的分页,必须给我两个参数。一个是要看哪一页,另一个是总记录条数
public PageModel(int currentPageNum,int totalRecords,int pageSize){
this.currentPageNum = currentPageNum;
this.totalRecords = totalRecords;
this.pageSize=pageSize;
//计算查询记录的开始索引
startIndex = (currentPageNum-1)*pageSize;
//计算总页数
totalPageNum = totalRecords%pageSize==0?(totalRecords/pageSize):(totalRecords/pageSize+1);
startPage = currentPageNum - 4; //5
endPage = currentPageNum + 4; //13
//看看总页数够不够9页
if(totalPageNum>9){
//超过了9页
if(startPage < 1){
startPage = 1;
endPage = startPage+8;
}
if(endPage>totalPageNum){
endPage = totalPageNum;
startPage = endPage-8;
}
}else{
//不够9页
startPage = 1;
endPage = totalPageNum;
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getPrePageNum() {
prePageNum = currentPageNum-1;
if(prePageNum<1){
prePageNum = 1;
}
return prePageNum;
}
public int getNextPageNum() {
nextPageNum = currentPageNum+1;
if(nextPageNum>totalPageNum){
nextPageNum = totalPageNum;
}
return nextPageNum;
}
public int getCurrentPageNum() {
return currentPageNum;
}
public void setCurrentPageNum(int currentPageNum) {
this.currentPageNum = currentPageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public int getTotalPageNum() {
return totalPageNum;
}
public void setTotalPageNum(int totalPageNum) {
this.totalPageNum = totalPageNum;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public void setPrePageNum(int prePageNum) {
this.prePageNum = prePageNum;
}
public void setNextPageNum(int nextPageNum) {
this.nextPageNum = nextPageNum;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
5.准备好页面
如下图
index页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<h1>分页demo</h1>
<h2><a href="${pageContext.request.contextPath }/FindAllServlet?num=1">分页展示所有的商品</a></h2>
</body>
</html>
运行:
分页展示所有的商品的实现:FIndAllServlet
package com.web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.domain.PageModel;
import com.domain.Product;
import com.service.ProductService;
/**
* Servlet implementation class FindAllServlet
*/
public class FindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从客户端获取参数
int num = Integer.parseInt(request.getParameter("num"));
//调用service层 完成查询
try {
PageModel pm = new ProductService().findAll(num);
request.setAttribute("page", pm);
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
调用service 完成实现
package com.service;
import java.sql.SQLException;
import java.util.List;
import com.dao.ProductDao;
import com.domain.PageModel;
import com.domain.Product;
public class ProductService {
public PageModel findAll(int num) throws SQLException {
ProductDao dao = new ProductDao();
//设置一页显示的商品个数
int pageSize = 3;
//获取总的商品个数
int totalRecords = dao.getTotalRecords();
//初始化模型
PageModel pm = new PageModel(num,totalRecords,pageSize);
//获取所有的商品
List list = dao.findAll(pm.getStartIndex(),pm.getPageSize());
pm.setList(list);
pm.setUrl("/FindAllServlet");
return pm;
}
}
dao层
package com.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.domain.Product;
import com.utils.DataSourceUtils;
public class ProductDao {
public int getTotalRecords() throws SQLException {
//创建QuertyRunner
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
// 编写sql语句
String sql = "select count(*) from product";
// 执行sql
return ((Long)qr.query(sql, new ScalarHandler())).intValue();
}
public List findAll(int startIndex, int pageSize) throws SQLException {
// 创建QuertyRunner
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
// 编写sql语句
String sql = "select * from product limit ?,?";
//为占位符赋值
Object[] params = {startIndex,pageSize};
// 执行sql
return qr.query(sql, new BeanListHandler<>(Product.class), params);
}
}
显示商品
<%@ 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>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
</head>
<body>
<table class="table table-hover">
<tr>
<td>商品编号</td>
<td>商品名称</td>
<td>市场价</td>
<td>商城价</td>
<td>商品图片</td>
<td>上市日期</td>
<td>商品描述</td>
</tr>
<c:forEach items="${page.list }" var="p">
<tr>
<td>${p.pid }</td>
<td>${p.pname }</td>
<td>${p.market_price }</td>
<td>${p.shop_price }</td>
<td>
<img src="${pageContext.request.contextPath }/${p.pimage}">
</td>
<td>${p.pdate }</td>
<td>${p.pdesc }</td>
</tr>
</c:forEach>
</table>
<%@ include file="/pageFile.jsp" %>
</body>
</html>
product_list.jsp包含pageFile.jsp(<%@ include file="/pageFile.jsp" %>)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="text-align: center">
当前第${page.currentPageNum}页/一共${page.totalPageNum}页/ <a
href="${pageContext.request.contextPath}/${page.url}?num=1">首页</a> <a
href="${pageContext.request.contextPath}/${page.url}?num=${page.prePageNum}">上一页</a>
<c:forEach begin="${page.startPage}" end="${page.endPage}"
var="pagenum">
<a
href="${pageContext.request.contextPath}/${page.url}?num=${pagenum}">${pagenum}</a>
</c:forEach>
<a
href="${pageContext.request.contextPath}/${page.url}?num=${page.nextPageNum}">下一页</a>
<a
href="${pageContext.request.contextPath}/${page.url}?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(){
var totalpage = ${page.totalPageNum};
var pagenum = document.getElementById("pagenum").value;
//判断输入的是一个数字
var reg =/^[1-9][0-9]{0,1}$/;
if(!reg.test(pagenum)){
//不是一个有效数字
alert("请输入符合规定的数字");
return ;
}
//判断输入的数字不能大于总页数
if(parseInt(pagenum)>parseInt(totalpage)){
//超过了总页数
alert("不能大于总页数");
return;
}
//转向分页显示的Servlet
window.location.href="${pageContext.request.contextPath}/${page.url}?num="+pagenum;
}
</script>
</div>
pageFile.jsp运行效果
整体效果