分頁分爲真分頁和假分頁;
假分頁就是還是一次性查到所有數據,但通過前端的一些技巧看起來像是在分頁,對數據庫一樣很有壓力;
真分頁就是利用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" onclick="getKey(this)">首頁</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage-1}" onclick="getKey(this)">上一頁</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage+1}" onclick="getKey(this)">下一頁</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.totalPage}" onclick="getKey(this)">尾頁</a>
</c:if>
<%-- 尾頁,只有 首頁 上一頁 --%>
<c:if test="${myPage.currentPage == myPage.totalPage && myPage.totalPage !=1}">
<a href="ShopServlet?operation=query¤tPage=1" onclick="getKey(this)">首頁</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage-1}" onclick="getKey(this)">上一頁</a>
</c:if>
<%-- 首頁,只有 下一頁 尾頁 --%>
<c:if test="${myPage.currentPage == 1 && myPage.totalPage !=1}">
<a href="ShopServlet?operation=query¤tPage=${myPage.currentPage+1}" onclick="getKey(this)">下一頁</a>
<a href="ShopServlet?operation=query¤tPage=${myPage.totalPage}" onclick="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環境下跑起來
主要是分頁功能的展示,其他就不展示啦
如果您覺得本文章對您有幫助,請點個贊支持一下作者~