基于分页插件的分页
程序员文章站
2024-03-24 16:32:10
...
一、技术
(1)后台:java、mysql
(2)前端:js、jquery、css、jstl、分页的插件(jquery.pagination.js)
二、思想
前端(页码)=>后台servlet(页码,页大小)=>后台service(页码,页大小)=>后台jdbc(开始行,页大小)=>数据库(开始行,页大小)
三、工程布局图
四、效果图
五、代码
1.com.oracle.dao包:
package com.oracle.dao;
import java.util.List;
import com.oracle.vo.Product;
public interface ProductDao {
//select * from product limit 0,5;
public List<Product> getUserByLimit(int startRow,int pageSize);
//查询 总记录数
public int getProductsCount();
}
========================
package com.oracle.dao;
import com.oracle.vo.User;
public interface UserDao {
public User getUser(String name,String password);
}
2.com.oracle.daoImpl包:
package com.oracle.daoImpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.oracle.dao.ProductDao;
import com.oracle.util.DBTools;
import com.oracle.vo.Product;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> getUserByLimit(int startRow, int pageSize) {
String sql = "select * from product limit ?,?";
List<Product> products = null;
try {
products = DBTools.queryMore(sql, Product.class, startRow,pageSize);
} catch (Exception e) {
e.printStackTrace();
}
return products;
}
@Override //sql 语句的 别名
public int getProductsCount() {
String sql = "select count(*) as count from product";
Connection conn = DBTools.getLocalConn();
PreparedStatement ps = null;
int count = 0;
try {
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
}
====================
package com.oracle.daoImpl;
import com.oracle.dao.UserDao;
import com.oracle.util.DBTools;
import com.oracle.vo.User;
public class UserDaoImpl implements UserDao {
@Override
public User getUser(String name, String password) {
String sql = "select * from user where name = ? and password = ?";
User user = null;
try {
user = DBTools.queryOne(sql, User.class, name,password);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
3.com.oracle.service包:
package com.oracle.service;
import com.oracle.vo.Pager;
import com.oracle.vo.Product;
/**
*
* 之前学习的 业务层 返回 集合 的 这件事 已经 结束了
* 从此以后 业务层 要返回一个
* 分页 对象 类名 为 :Pager/Pagination:
* 分页对象中 包含: 之前的 回显数据 和 页面的 页码,总页数的相关信息
*
* @author Administrator
*
*/
public interface ProductService {
public Pager<Product> getProductsByLimit(int pageNo,int pageSize);
}
===================
package com.oracle.service;
import com.oracle.vo.User;
/**
* 业务层
* @author Administrator
*
*/
public interface UserService {
//登录
public User login(String name,String password);
}
4.com.oracle.serviceImpl包:
package com.oracle.serviceImpl;
import java.util.List;
import com.oracle.dao.ProductDao;
import com.oracle.daoImpl.ProductDaoImpl;
import com.oracle.service.ProductService;
import com.oracle.vo.Pager;
import com.oracle.vo.Product;
public class ProductServiceImpl implements ProductService {
ProductDao ps = new ProductDaoImpl();
@Override
public Pager<Product> getProductsByLimit(int pageNo, int pageSize) {
//计算 开始行
int startRow = (pageNo- 1)*pageSize;
List<Product> products = ps.getUserByLimit(startRow, pageSize);
//select count(*) from product;
//获取 数据库的 总记录数
int totalRecord = ps.getProductsCount();
Pager<Product> pager = new Pager<>(pageNo, pageSize, totalRecord, products);
return pager;
}
}
=====================
package com.oracle.serviceImpl;
import com.oracle.dao.UserDao;
import com.oracle.daoImpl.UserDaoImpl;
import com.oracle.service.UserService;
import com.oracle.vo.User;
public class UserServiceImpl implements UserService{
UserDao userDao = new UserDaoImpl();
//登录
@Override
public User login(String name, String password) {
return userDao.getUser(name, password);
}
}
5.com.oracle.servlet包:
package com.oracle.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oracle.service.ProductService;
import com.oracle.serviceImpl.ProductServiceImpl;
import com.oracle.vo.Pager;
import com.oracle.vo.Product;
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = -318134993070614515L;
private ProductService ps = new ProductServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String flag = request.getParameter("flag");
if("pageForm".equals(flag)){
String pageNumStr = request.getParameter("pageNum");
if(null == pageNumStr) {
pageNumStr="1";
}
int pageNum = Integer.parseInt(pageNumStr);
Pager<Product> result = ps.getProductsByLimit(pageNum, 5);
session.setAttribute("pager", result);
//response.sendRedirect("main.jsp");
response.getWriter().write("success");
}else{
String pageNumStr = request.getParameter("pageNum");
if(null == pageNumStr) {
pageNumStr="1";
}
int pageNum = Integer.parseInt(pageNumStr);
Pager<Product> result = ps.getProductsByLimit(pageNum, 5);
session.setAttribute("pager", result);
response.sendRedirect("main.jsp");
}
}
}
======================
package com.oracle.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oracle.service.UserService;
import com.oracle.serviceImpl.UserServiceImpl;
import com.oracle.vo.User;
public class UserServlet extends HttpServlet {
UserService us =new UserServiceImpl();
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//servlet 就是用来接收 页面的请求的
String name = request.getParameter("name");
String pwd = request.getParameter("password");
HttpSession session = request.getSession();
User user = us.login(name, pwd);
if(null != user){
//存session
session.setAttribute("user", user);
//登录成功 去 productServlet
request.getRequestDispatcher("productServlet").forward(request, response);
}
}
}
6.com.oracle.util
package com.oracle.util;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DBTools {
// ? 是用来携带参数的 & 多个参数 连接
private static String DRIVER = null;
private static String URL = null;
private static String USERNAME = null;
private static String PASSWORD = null;
static Connection conn = null;
private static ThreadLocal<Connection> local = new ThreadLocal<>();
private static PreparedStatement ps;
private static ResultSet rs;
static {
try {
// 内容 在 db.properties 文件中
InputStream ips = DBTools.class.getClassLoader().getResourceAsStream("config/db.properties");
Properties p = new Properties();
// 加载 流
p.load(ips);
DRIVER = p.getProperty("jdbc.driver");
URL = p.getProperty("jdbc.url");
USERNAME = p.getProperty("jdbc.username");
PASSWORD = p.getProperty("jdbc.password");
Class.forName(DRIVER);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getLocalConn() {
// 先在 ThreadLocal 类中取连接
Connection conn = local.get();
if (null == conn) {
// 如果 为空 就 设置一个 连接
local.set(DBTools.getConn());
// 在取出 刚才 设置的连接
conn = local.get();
}
// 返回
return conn;
}
public static Connection getConn() {
// 使用 驱动 管理器 获取 连接
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (null != conn) {
conn.close();
}
} catch (Exception e) {
System.out.println("资源未关闭");
}
}
/**
* 完成 DML 操作
*
* preparedStatement();
*
* insert into update delete
*
* @throws SQLException
*
*/
public static boolean executeUpdate(String sql, Object... args) throws Exception {
conn = DBTools.getLocalConn();
ps = conn.prepareStatement(sql);
// 给 ? 赋值
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
// 执行sql语句
int a = ps.executeUpdate();
return a > 0 ? true : false;
}
/**
* 查询一条记录 select * from user where id = ?; select * from user where uname =
* ? and password = ?;
*
* @throws Exception
*/
public static <T> T queryOne(String sql, Class<T> c, Object... args) throws Exception {
conn = DBTools.getLocalConn();
ps = conn.prepareStatement(sql);
// 给 ? 赋值
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
// 通过 结果集 获取 元数据
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
T t = null;
while (rs.next()) {
t = c.newInstance();
for (int i = 1; i <= count; i++) {
String col_name = metaData.getColumnName(i);
Object col_value = rs.getObject(i);
Field field = c.getDeclaredField(col_name);
// 设置属性的访问权限 注释 : 因为 set 方法 只适用于 public修饰的 属性
field.setAccessible(true);
// 给当前属性赋值
field.set(t, col_value);
}
}
return t;
}
/**
* 查询多条记录
* select * from user; select * from user where uname like ? select *
* from user where uname like ? limit ?,?
*
* @throws Exception
*
*/
public static <T> List<T> queryMore(String sql, Class<T> c, Object... args) throws Exception {
List<T> list = new ArrayList<>();
conn = DBTools.getLocalConn();
ps = conn.prepareStatement(sql);
// 给 ? 赋值
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
// 通过 结果集 获取 元数据
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
T t = null;
while (rs.next()) {
t = c.newInstance();
for (int i = 1; i <= count; i++) {
String col_name = metaData.getColumnName(i);
Object col_value = rs.getObject(i);
Field field = c.getDeclaredField(col_name);
// 设置属性的访问权限 注释 : 因为 set 方法 只适用于 public修饰的 属性
field.setAccessible(true);
// 给当前属性赋值
field.set(t, col_value);
}
list.add(t);
}
return list;
}
public static <T> List<T> queryMoreTwo(String sql, Class<T> c, List<Object> lists) throws Exception {
List<T> list = new ArrayList<>();
conn = DBTools.getLocalConn();
ps = conn.prepareStatement(sql);
// 给 ? 赋值
for (int i = 0; i < lists.size(); i++) {
ps.setObject(i + 1, lists.get(i));
}
rs = ps.executeQuery();
// 通过 结果集 获取 元数据
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
T t = null;
while (rs.next()) {
t = c.newInstance();
for (int i = 1; i <= count; i++) {
String col_name = metaData.getColumnName(i);
Object col_value = rs.getObject(i);
Field field = c.getDeclaredField(col_name);
// 设置属性的访问权限 注释 : 因为 set 方法 只适用于 public修饰的 属性
field.setAccessible(true);
// 给当前属性赋值
field.set(t, col_value);
}
list.add(t);
}
return list;
}
}
==========================
package com.oracle.util;
/**
* 常量类
*/
public class Constants {
public static final int PAGE_SIZE = 5;
}
====================
package com.oracle.util;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
/**
* 自定义 封装 工具类 将 页面中的 数据 封装到 vo | pojo | entity 实体中
*
* 前提 : input 标签中的 name属性名 必须域 vo 实体中的属性名 一致
*
*/
public class BeanUtil {
//获取有 值的 实体了
public static void getBean(Object obj,HttpServletRequest request){
try {
BeanUtils.populate(obj, request.getParameterMap());
} catch (Exception e) {
e.printStackTrace();
}
}
}
7.com.oracle.vo
package com.oracle.vo;
import java.io.Serializable;
import java.util.List;
/**
* 将 数据 和 页码 相关的信息 都 整合在 这个 实体类中
*/
public class Pager<T> implements Serializable{
private static final long serialVersionUID = 1L;
private Integer pageNo;//页码 用户 点击 的 第几页
private Integer pageSize;// 页 大小 每 页 多少条记录
private Integer currentPage; //当前页
private Integer totalPage; //总页数
private Integer totalRecord; //总 记录数 数据库 数据条数
private List<T> list;
public Pager() {
}
public Pager(Integer pageNo, Integer pageSize, Integer totalRecord,
List<T> list) {
//页码
this.pageNo = pageNo;
//页大小
this.pageSize = pageSize;
//总记录数
this.totalRecord = totalRecord;
//总页数
this.totalPage = this.totalRecord / this.pageSize;
if(this.totalRecord % this.pageSize != 0 ){
this.totalPage = this.totalPage + 1;
}
//当前页
this.currentPage = this.totalPage < pageNo ? this.totalPage : pageNo;
//数据
this.list = list;
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(Integer totalRecord) {
this.totalRecord = totalRecord;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
====================
package com.oracle.vo;
import java.io.Serializable;
public class Product implements Serializable{
private Integer id;
private String pname;
private Double price;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "Product [id=" + id + ", pname=" + pname + ", price=" + price + ", remark=" + remark + "]";
}
}
=======================
package com.oracle.vo;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String name;
private Integer age;
private Integer gender;
private String password;
private String realName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", password=" + password
+ ", realName=" + realName + "]";
}
}
前端
1.css
/PagerDemo/WebContent/css/pagination.css
.pagination {
font-size: 80%;
}
.pagination a {
text-decoration: none;
border: solid 1px #AAE;
color: #15B;
}
.pagination a, .pagination span {
display: block;
float: left;
padding: 0.3em 0.5em;
margin-right: 5px;
margin-bottom: 5px;
min-width:1em;
text-align:center;
}
.pagination .current {
background: #26B;
color: #fff;
border: solid 1px #AAE;
}
.pagination .current.prev, .pagination .current.next{
color:#999;
border-color:#999;
background:#fff;
}
2./PagerDemo/WebContent/login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="top.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/test.css">
<title>登录</title>
</head>
<body>
<form action="userServlet" method="post">
<input type="hidden" value="login" name="flag">
<span><font color="red">${flag==false?"用户或密码错误":"" }</font></span><br/>
用户名:
<input type="text" name="name" value="${sessionScope.user.name }">
<br/>
密码:
<input type="text" name="password" value="${sessionScope.user.password }">
<br/>
記住用戶名: <input type="checkbox" name="remeber" ${sessionScope.remember==1 ? "checked" : ""}/><br/>
<input type="submit" value="提交" />
<a href="register.jsp" >注册</a>
</form>
</body>
</html>
3./PagerDemo/WebContent/main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="top.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<link type="text/css" rel="stylesheet" href="css/pagination.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页</title>
</head>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery.pagination.js"></script>
<script type="text/javascript">
function handlePaginationClick(new_page_index,pagination_container){
$.ajax({
data: {pageNum: new_page_index+1, flag: "pageForm"},
type: "POST",
url: "productServlet",
success: function(data){
if(data == "success"){
$("body").load("main.jsp");
}
}
});
return false;
}
$(function(){
//第一个 参数 时 总记录数 pager.totalRecord
$("#News-Pagination").pagination(${pager.totalRecord },{
items_per_page:${pager.pageSize}, // 每页显示多少条记录
current_page:${pager.currentPage} - 1, // 当前显示第几页数据
num_display_entries:3, // 分页显示的条目数
next_text:"下一页",
prev_text:"上一页",
load_first_page:false,
num_edge_entries:2, // 连接分页主体,显示的条目数
callback:handlePaginationClick
});
})
</script>
<body>
<table>
<tr>
<th>全选<input type="checkbox" name="checkAll">
<th>商品编号</th>
<th>商品名称</th>
<th>商品价钱</th>
<th>商品描述</th>
<th>操作</th>
</tr>
<c:forEach items="${pager.list }" var="product">
<tr>
<th><input type="checkbox" name="checkOne">
<th>${product.id }</th>
<th>${product.pname }</th>
<th>${product.price }</th>
<th>${product.remark }</th>
</tr>
</c:forEach>
</table>
<div id="News-Pagination"></div>
</body>
</html>
4./PagerDemo/WebContent/top.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
5.ajax
ajax :页面的 局部刷新 异步请求
原生的 js写法
基于 jquery的 ajax 写法
form ,a , button 都可以用 ajax 来完成 对后台对的请求
<form action="userServlet">
<input type="button" value="登录">
<input type="submit value="登录">
</form>
选择了 ajax 提交 不用 自动提交
a
button
================================
前提 是 你已经 导入了 jquery-3.4.1.min.js 文件
$(function(){
$("").click(function(){
$.ajax({
data:传输到后台的数据,
type:"请求方式 get / post",
url:"目标地址",
success:function(){
//回调函数
},
error:function(){
}
});
$.post();
$.get();
$.getJSON(); 只可以接收 json格式
$.load("就使来发送请求 和 加载页面");
})
})
//必须触发 或 调用
function nextPage(){
$.ajax({
data:传输到后台的数据,
type:"请求方式 get / post",
url:"目标地址",
success:function(){
//回调函数
},
error:function(){
}
});
$.post();
$.get();
$.getJSON(); 只可以接收 json格式
$.load("就使来发送请求 和 加载页面");
}
===============
$.post("productServlet?flag=pageForm&pageNum="+(new_page_index+1),function(data){
$.load("main.jsp");
});
$.ajax({
data: {pageNum:new_page_index+1&flag'pageForm'},
type: "POST",
url: "productServlet",
success: function(data){
alert(data);
$.load("main.jsp");
}
});
$.load("productServlet?flag=pageForm&pageNum="+(new_page_index+1),function(){
$.load("main.jsp");
});
方法一
1)function handlePaginationClick(new_page_index,pagination_container){
$.get("productServlet",{pageNum: new_page_index+1, flag: "pageForm"},function(data){
$("body").load("main.jsp");
});
return false;
}
2)function handlePaginationClick(new_page_index,pagination_container){
$.get("productServlet?flag=pageForm&pageNum="+(new_page_index+1),function(data){
$("body").load("main.jsp");
});
return false;
}
方法二
1)function handlePaginationClick(new_page_index,pagination_container){
$.post("productServlet",{pageNum: new_page_index+1, flag: "pageForm"},function(data){
$("body").load("main.jsp");
});
return false;
}
2)function handlePaginationClick(new_page_index,pagination_container){
$.post("productServlet?flag=pageForm&pageNum="+(new_page_index+1),function(data){
$("body").load("main.jsp");
});
return false;
}
方法三
1)function handlePaginationClick(new_page_index,pagination_container){
$.ajax({
data: {pageNum: new_page_index+1, flag: "pageForm"},
type: "POST",
url: "productServlet",
success: function(data){
$("body").load("main.jsp");
}
});
return false;
}
2)function handlePaginationClick(new_page_index,pagination_container){
$.ajax({
data: {pageNum: new_page_index+1, flag: "pageForm"},
type: "GET",
url: "productServlet",
success: function(data){
$("body").load("main.jsp");
}
});
return false;
}
3)function handlePaginationClick(new_page_index,pagination_container){
$("#main").load("productServlet",{pageNum: new_page_index+1, flag: "pageForm"},function(){
$("body").load("main.jsp");
});
return false;
}
上一篇: Mybatis的分页插件
推荐阅读
-
mybatis分页和PageHelper插件的使用
-
mybatis的分页插件
-
基于分页插件的分页
-
Mybatis的分页插件
-
MyBatis中乐观锁插件和分页插件的使用
-
数据库的分页技术 博客分类: 数据库 SQL Serveroraclemysql
-
ThinkPHP5.0 分页的使用
-
基于asp.net + easyui框架,一步步学习easyui-datagrid——实现分页和搜索(二) 博客分类: 【EasyUI】 asp.net框架jsonjavascript
-
用iview的表格方式封装element中的table表格和分页
-
【EasyExcel】封装一个分页写数据的通用方法,有效规避OOM