分页分为真分页和假分页;
假分页就是还是一次性查到所有数据,但通过前端的一些技巧看起来像是在分页,对数据库一样很有压力;
真分页就是利用limit在查询的时候的限制,每次查的就是这么多数据;
本章讲述的是在纯MVC环境下,在条件查询的情况下添加分页。例子就是一个简单的商品增删查改。
首先介绍一下具体的层次
1.构建分页实体类Page(使用了泛型,可以在多种对象中复用)
由于总条数一定是要去数据库每次都查一遍的,那么就在调setTotalPage的时候一次性计算完page的所有属性。
package org.hc.homework.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//分页
public class Page<T> implements Serializable {
private static final long serialVersionUID = -4147209130619898593L;
private int pageSize;//每页的条数,也是limit读取的个数
private int currentPage;//当前页号
private int totalCount;//总条数——从数据库中拿到
private int start;//数据库limit开始条数 = (currentPage-1)*pageSize
private int totalPage;//总页数 = 总条数/每页的条数
private List<T> lists=new ArrayList<>();//用于存储数据库查出的数据
public List<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
if (currentPage <= 0) {
this.currentPage = 1;
} else {
this.currentPage = currentPage;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {//在set总条数的时候将所有数据全部计算完成
this.totalCount = totalCount;
//总页数的计算
if (totalCount / pageSize <1) {
this.totalPage = 1;
} else if (totalCount % pageSize == 0) {
this.totalPage = totalCount / pageSize;
} else {
this.totalPage = totalCount / pageSize + 1;
}
//limit开始序号的计算
this.start = (currentPage - 1) * pageSize;
}
public int getTotalPage() {
return totalPage;
}
public int getStart() {
return start;
}
}
1.1 实体类Shop
package org.hc.homework.entity;
import java.io.Serializable;
//数据库具体属性
/* `no` varchar(50) NOT NULL,
`name` varchar(50) NOT NULL,
`time` varchar(50) NOT NULL,
`address` varchar(50) NOT NULL,
`type` varchar(50) NOT NULL,*/
public class Shop implements Serializable {
private static final long serialVersionUID = -3998521295785926249L;
private String no;
private String name;
private String time;
private String address;
private String type;
public Shop(String no, String name, String time, String address, String type) {
this.no = no;
this.name = name;
this.time = time;
this.address = address;
this.type = type;
}
public Shop(){}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
2.MYSQL连接工具类 JdbcUtil (根据实际情况更改)
package org.hc.homework.utils;
import java.sql.*;
public class JdbcUtil {
//数据库驱动类
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
//数据库的连接地址
public static final String URL = "jdbc:mysql://localhost:3306/javawebjdbcdemo?serverTimezone=UTC";
//账号
public static final String UID = "root";
//密码
public static final String PWD = "123";
//获取Connection实例
public static Connection getCon() {
Connection con = null;
try {
Class.forName(DRIVER);//ClassNotFoundException
con = DriverManager.getConnection(URL, UID, PWD);//SQLException
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//关闭Connection对象
public static void closeCon(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.数据访问层 dao
ShopDao
package org.hc.homework.dao;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
public interface ShopDao {
//查询——添加分页功能 增加新参数Page page
Page<Shop> getShopsInPage(Page<Shop> page);
//查询 BY no
Shop getShopByNo(String no);
//查询条件查询总条数
int getCount(Shop shop);
//删除
boolean deleteShop(String no);
//修改
boolean updateShop(Shop shop, String updateNo);
//新增
boolean addShop(Shop shop);
}
ShopDaoImpl
package org.hc.homework.dao.daoImpl;
import org.hc.homework.dao.ShopDao;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.utils.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ShopDaoImpl implements ShopDao {
//jdbc API
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
//查询 -全查 -模糊查询 -分页
@Override
public Page<Shop> getShopsInPage(Page<Shop> page) {
try {
List<Shop> shops = new ArrayList<>();//符合查询条件的数据会放在这个集合中,最后放入page.setList()里
List<String> wenhao = new ArrayList<>();//问号替换的集合
Shop newshop = new Shop();//每一行数据
StringBuffer sql = new StringBuffer("select * from shop where 1=1");
//从page中拿出查询条件
if (page.getLists().size() != 0) {
newshop = page.getLists().get(0);
}
//条件查询添加的sql
if (newshop.getType() != null) {
//type精确查询
if (newshop.getType() != null && !newshop.getType().trim().isEmpty()) {
sql.append(" and type like ? ");
wenhao.add("%" + newshop.getType() + "%");
}
//name模糊查询
if (newshop.getName() != null && !newshop.getName().trim().isEmpty()) {
sql.append(" and name like ? ");
wenhao.add("%" + newshop.getName() + "%");
}
//address模糊查询
if (newshop.getAddress() != null && !newshop.getAddress().trim().isEmpty()) {
sql.append(" and address like ? ");
wenhao.add("%" + newshop.getAddress() + "%");
}
//time模糊查询
if (newshop.getTime() != null && !newshop.getTime().trim().isEmpty()) {
sql.append(" and time like ? ");
wenhao.add("%" + newshop.getTime() + "%");
}
}
//分页添加的sql 由于limit只能放在where结束后,所以放在这里
sql.append(" limit ?,?");
//预编译后,将所有问号依次替换
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql.toString());
//只把除limit的两个问号都替换掉
for (int i = 0; i < wenhao.size(); i++) {
ps.setString(i + 1, wenhao.get(i));
}
//替换limit的两个问号
ps.setInt(wenhao.size() + 1, page.getStart());
ps.setInt(wenhao.size() + 2, page.getPageSize());
rs = ps.executeQuery();
while (rs.next()) {
newshop = new Shop(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)
);
shops.add(newshop);
page.setLists(shops);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return page;
}
//单行查询 通过no
@Override
public Shop getShopByNo(String no) {
Shop shop = null;
try {
String sql = "select * from shop where no=?";
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql);
ps.setString(1, no);
rs = ps.executeQuery();
if (rs.next()) {
shop = new Shop(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)
);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return shop;
}
//count需要根据条件查询改变
@Override
public int getCount(Shop shop) {
int count = 0;
try {
ArrayList<String> wenhao = new ArrayList<>();//问号替换的集合
StringBuffer sql = new StringBuffer("select count(*) from shop where 1=1 ");
if (shop != null) {
//type精确查询
if (shop.getType() != null && !shop.getType().trim().isEmpty()) {
sql.append(" and type like ? ");
wenhao.add("%" + shop.getType() + "%");
}
//name模糊查询
if (shop.getName() != null && !shop.getName().trim().isEmpty()) {
sql.append(" and name like ? ");
wenhao.add("%" + shop.getName() + "%");
}
//address模糊查询
if (shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) {
sql.append(" and address like ? ");
wenhao.add("%" + shop.getAddress() + "%");
}
//time模糊查询
if (shop.getTime() != null && !shop.getTime().trim().isEmpty()) {
sql.append(" and time like ? ");
wenhao.add("%" + shop.getTime() + "%");
}
}
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql.toString());
//替换问号
for (int i = 0; i < wenhao.size(); i++) {
ps.setString(i + 1, wenhao.get(i));
}
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return count;
}
//删除 通过no
@Override
public boolean deleteShop(String no) {
try {
String sql = "delete from shop where no=?";
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql);
ps.setString(1, no);
ps.execute();
return true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return false;
}
//修改 通过shop对象 where=no
@Override
public boolean updateShop(Shop shop, String updateNo) {
try {
String sql = "update shop set no=?,name=?,address=?,type=? where no =?";
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql);
ps.setString(1, shop.getNo());
ps.setString(2, shop.getName());
ps.setString(3, shop.getAddress());
ps.setString(4, shop.getType());
ps.setString(5, updateNo);
ps.execute();
return true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return false;
}
//新增
@Override
public boolean addShop(Shop shop) {
try {
String sql = "insert into shop values(?,?,?,?,?)";
con = JdbcUtil.getCon();
ps = con.prepareStatement(sql);
ps.setString(1, shop.getNo());
ps.setString(2, shop.getName());
ps.setString(3, shop.getTime());
ps.setString(4, shop.getAddress());
ps.setString(5, shop.getType());
ps.execute();
return true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeCon(con, ps, rs);
}
return false;
}
}
4.业务逻辑层 service
ShopService
package org.hc.homework.service;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
public interface ShopService {
//查询-分页
Page<Shop> getShopsInPage(Page<Shop> page);
//查询 BY no
Shop getShopByNo(String no);
//删除
boolean deleteShop(String no);
//修改
boolean updateShop(Shop shop, String updateNo);
//新增
boolean addShop(Shop shop);
}
ShopServiceImpl
package org.hc.homework.service.serviceImpl;
import org.hc.homework.dao.ShopDao;
import org.hc.homework.dao.daoImpl.ShopDaoImpl;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.service.ShopService;
public class ShopServiceImpl implements ShopService {
ShopDao shopDao=new ShopDaoImpl();
@Override
public Page<Shop> getShopsInPage(Page<Shop> page) {
if (page.getLists().size()==0){
page.setTotalCount(shopDao.getCount(new Shop()));//总条数赋值进去
}else{
page.setTotalCount(shopDao.getCount(page.getLists().get(0)));//总条数赋值进去
}
return shopDao.getShopsInPage(page);
}
@Override
public Shop getShopByNo(String no) {
return shopDao.getShopByNo(no);
}
@Override
public boolean deleteShop(String no) {
return shopDao.deleteShop(no);
}
@Override
public boolean updateShop(Shop shop, String updateNo) {
return shopDao.updateShop(shop,updateNo);
}
@Override
public boolean addShop(Shop shop) {
return shopDao.addShop(shop);
}
}
5.控制层 Servlet
通过每次跳到控制器的opereation的值决定是哪个操作
package org.hc.homework.servlet;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.service.ShopService;
import org.hc.homework.service.serviceImpl.ShopServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet(name = "ShopServlet")
public class ShopServlet extends HttpServlet {
private static final long serialVersionUID = -6283161696285843678L;
ShopService shopService = new ShopServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
ArrayList<Shop> shops = null;
String operation = request.getParameter("operation");//操作字符
Page<Shop> page = new Page();
if (request.getParameter("currentPage") != null) {
page.setCurrentPage(Integer.parseInt(request.getParameter("currentPage")));//当前页
} else {
page.setCurrentPage(1);
}
if (request.getParameter("pageSize") != null) {
page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));//每页的条数
} else {
page.setPageSize(4);
}
//判断业务
if (operation.equals("queryAll")) {
//全查
page = shopService.getShopsInPage(page);
} else if (operation.equals("query")) {
//条件查询
Shop shop = new Shop(
null,
request.getParameter("name"),
request.getParameter("time"),
request.getParameter("address"),
request.getParameter("type")
);
request.setAttribute("queryShop", shop);
page.getLists().add(shop);
page = shopService.getShopsInPage(page);
//测试
log("条件查询page的各个属性:" +
"\npage.getTotalCount=" + page.getTotalCount() +
"\npage.getPageSize=" + page.getPageSize() +
"\npage.getStart=" + page.getStart() +
"\npage.getCurrentPage=" + page.getCurrentPage() +
"\npage.getName=" + shop.getName() +
"\npage.getType=" + shop.getType() +
"\npage.getTime=" + shop.getTime() +
"\npage.getAddress=" + shop.getAddress()
);
} else if (operation.split("&")[0].equals("delete")) {
//删除,由&拆分字符串,拿下标为0的数组内容
String no = operation.split("&")[1];
boolean flag = shopService.deleteShop(no);
if (flag) {
request.setAttribute("Success", "<script>alert('删除成功')</script>");
} else {
request.setAttribute("Success", "<script>alert('ERROR!服务器错误')</script>");
}
page = shopService.getShopsInPage(page);//全查
} else if (operation.split("&")[0].equals("toUpdate")) {
//to修改,由&拆分字符串,拿下标为0的数组内容
String no = operation.split("&")[1];
Shop shop = shopService.getShopByNo(no);
request.setAttribute("shop", shop);//返回原数据
request.getRequestDispatcher("updateList.jsp").forward(request, response);
return;
} else if (operation.equals("update")) {
//修改
String updateNo = request.getParameter("updateNo");
Shop shop = new Shop(
request.getParameter("no"),
request.getParameter("name"),
request.getParameter("time"),
request.getParameter("address"),
request.getParameter("type")
);
boolean flag = shopService.updateShop(shop, updateNo);
if (flag) {
request.setAttribute("Success", "<script>alert('修改成功')</script>");
} else {
request.setAttribute("Success", "<script>alert('ERROR!服务器错误')</script>");
}
page = shopService.getShopsInPage(page);//全查
} else if (operation.equals("add")) {
//新增
Shop shop = new Shop(
request.getParameter("no"),
request.getParameter("name"),
request.getParameter("time"),
request.getParameter("address"),
request.getParameter("type")
);
boolean flag = shopService.addShop(shop);
if (flag) {
request.setAttribute("Success", "<script>alert('新增成功')</script>");
} else {
request.setAttribute("Success", "<script>alert('ERROR!服务器错误')</script>");
}
page = shopService.getShopsInPage(page);//全查
} else if (operation.equals("toAdd")) {
//to新增
request.getRequestDispatcher("addList.jsp").forward(request, response);
return;
}
request.setAttribute("page", page);
request.getRequestDispatcher("list.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
java类就在此结束了,下面是JSP和CSS
6.JSP和CSS
center.css
body,div,table,form{
margin: 0 auto;
text-align: center;
}
#div1{
margin-top: 30px;
}
#div2{
margin-top: 50px;
}
#list{
margin-top: 20px;
}
index.jsp(初始界面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>welcome</title>
</head>
<body>
<form action="ShopServlet" method="post">
<button type="submit" value="列表">列表</button>
<input type="hidden" value="queryAll" name="operation">
</form>
</body>
</html>
list.jsp(全查列表)使用了EL表达式和JSTL,需要导入JSTL的包
<%@ page contentType="text/html;charset=UTF-8" %>
<%-- 引入JSTL --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="UTF-8">
<title>列表</title>
<link type="text/css" rel="stylesheet" href="css/center.css">
</head>
<%--是否删除、修改、新增成功--%>
<c:if test="${Success != null}">
${Success}
</c:if>
<body>
<%-- 搜索,条件查询 operation=qeury --%>
<div id="div1">
<form action="ShopServlet" method="post">
商品名:<input type="text" name="name" id="name" value="${queryShop.name}">
商品种类:<input type="text" name="type" id="type" value="${queryShop.type}">
产地:<input type="text" name="address" id="address" value="${queryShop.address}">
生产日期:<input type="text" name="time" id="time" value="${queryShop.time}">
<input type="hidden" name="operation" value="query">
<button type="submit">搜索</button>
</form>
</div>
<%-- 新增 --%>
<div id="div2">
<form action="ShopServlet" method="post">
<input type="hidden" name="operation" value="toAdd">
<button type="submit" style="width: 100px">新增商品信息</button>
</form>
</div>
<%--列表--%>
<div id="list">
<form action="ShopServlet" method="post">
<table border="1" cellspacing="0" cellpadding="5" style="text-align: center;margin: 0 auto">
<tr>
<td>商品编号</td>
<td>商品名</td>
<td>生产日期</td>
<td>产地</td>
<td>商品类型</td>
<td>删除</td>
<td>修改</td>
</tr>
<c:forEach items="${myPage.lists}" var="shop">
<tr>
<td>${shop.no}</td>
<td>${shop.name}</td>
<td>${shop.time}</td>
<td>${shop.address}</td>
<td>${shop.type}</td>
<td>
<button type="submit" name="operation" value="delete&${shop.no}">删除</button>
</td>
<td>
<button type="submit" name="operation" value="toUpdate&${shop.no}">修改</button>
</td>
</tr>
</c:forEach>
</table>
</form>
</div>
<div>
<%-- 不是首页和尾页,即中间页,即 首页 上一页 下一页 尾页 --%>
<c:if test="${myPage.currentPage>1 && myPage.currentPage<myPage.totalPage}">
<a href="ShopServlet?operation=query¤tPage=1" οnclick="getKey(this)">首页</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage-1}" οnclick="getKey(this)">上一页</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage+1}" οnclick="getKey(this)">下一页</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.totalPage}" οnclick="getKey(this)">尾页</a>
</c:if>
<%-- 尾页,只有 首页 上一页 --%>
<c:if test="${myPage.currentPage == myPage.totalPage && myPage.totalPage !=1}">
<a href="ShopServlet?operation=query¤tPage=1" οnclick="getKey(this)">首页</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage-1}" οnclick="getKey(this)">上一页</a>
</c:if>
<%-- 首页,只有 下一页 尾页 --%>
<c:if test="${myPage.currentPage == 1 && myPage.totalPage !=1}">
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage+1}" οnclick="getKey(this)">下一页</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.totalPage}" οnclick="getKey(this)">尾页</a>
</c:if>
</div>
<script>
function getKey(a) {
var name = document.getElementById("name").value;
var type = document.getElementById("type").value;
var address = document.getElementById("address").value;
var time = document.getElementById("time").value;
a.href += "&name=" + name + "&type=" + type + "&address=" + address + "&time=" + time;
}
</script>
</body>
</html>
addList.jsp(新增页面)
<%@ page contentType="text/html;charset=UTF-8"
language="java"
import="org.hc.homework.entity.Shop"
%>
<html>
<head>
<title>新增</title>
<link type="text/css" rel="stylesheet" href="css/center.css">
</head>
<body>
<div>
<form action="ShopServlet" method="post">
<input type="hidden" value="add" name="operation">
<table>
<tr>
<td colspan="2">新增商品信息</td>
<td colspan="2">
<button type="submit">确定</button>
</td>
</tr>
<tr>
<td>商品编号</td>
<td><input type="text" value="" name="no"></td>
<td>商品名称</td>
<td><input type="text" value="" name="name"></td>
</tr>
<tr>
<td>商品产地</td>
<td><input type="text" value="" name="address"></td>
<td>商品类型</td>
<td><input type="text" value="" name="type"></td>
</tr>
<tr>
<td>生产日期</td>
<td><input type="text" value="" name="time"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
updateList.jsp(修改页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%-- 引入JSTL --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>修改</title>
<link type="text/css" rel="stylesheet" href="css/center.css">
</head>
<body>
<div>
<form action="ShopServlet" method="post">
<input type="hidden" value="${shop.no}" name="updateNo">
<input type="hidden" value="update" name="operation">
<table>
<tr>
<td colspan="2">修改商品信息</td>
<td colspan="2">
<button type="submit">确定</button>
</td>
</tr>
<tr>
<td>商品编号</td>
<td><input type="text" value="${shop.no}" name="no"></td>
<td>商品名称</td>
<td><input type="text" value="${shop.name}" name="name"></td>
</tr>
<tr>
<td>商品产地</td>
<td><input type="text" value="${shop.address}" name="address"></td>
<td>商品类型</td>
<td><input type="text" value="${shop.type}" name="type"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
7.在tomcat环境下跑起来
主要是分页功能的展示,其他就不展示啦
如果您觉得本文章对您有帮助,请点个赞支持一下作者~