分页查询:
PageBean的主要属性:
totalCount 页面展示的数据的总条数,通过数据库查询
totalPage 数据分页的总页数,计算获得( Math.ceil向上取整(总条数/(每页显示的条数*1.0))
rows 每页显示的行数,自定义
currentPage 当前页码,由前端获取
List<Student> list 显示数据的内容,数据库获取
Student的主要属性:
id 学生id
name 学生姓名
age学生年龄
代码:
Servlet:用于获取数据
package com.xmcc.servlet;
import com.xmcc.entiy.Page;
import com.xmcc.entiy.Student;
import com.xmcc.service.StudentService;
import com.xmcc.service.lmpl.StudentServicelmpl;
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.*;
@WebServlet(name = "Servlet" ,value = "/Servlet")
public class Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentService studentService = new StudentServicelmpl();
response.setContentType("text/html;charset=utf-8");
String currentPage = request.getParameter("currentPage");
String curremtPagelast = request.getParameter("curremtPagelast");
String curremtPagenext = request.getParameter("curremtPagenext");
//控制上下页
if(curremtPagelast != null)//控制上一页
{
int curremtPagelast1 = Integer.parseInt(curremtPagelast);
System.out.println(curremtPagelast1);
currentPage = String.valueOf(curremtPagelast1-1);
System.out.println("这是上一页="+currentPage);
}
if(curremtPagenext !=null)//控制下一页
{
int curremtPagenext1 = Integer.parseInt(curremtPagenext);
System.out.println(curremtPagenext1);
currentPage = String.valueOf(curremtPagenext1+1);
System.out.println("这是下一页="+currentPage);
}
if(currentPage == null){//如果当前页数是空,设置页数为1
currentPage = "1";
}
//将studentService里面的getStudentsByPage方法的结果返回到Page中,“3”为每页保存的数据数
Page page = studentService.getStudentsByPage(3, Integer.parseInt(currentPage));
request.getSession().setAttribute("pb", page);//将数据保存到Seesion中
request.getSession().setAttribute("page", currentPage);
response.sendRedirect("/index.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response );
}
}
StudentService:
package com.xmcc.service;
import com.xmcc.entiy.Admin;
import com.xmcc.entiy.Page;
import com.xmcc.entiy.Student;
import java.util.ArrayList;
import java.util.List;
public interface StudentService {
List<Student> getStudent() ;
Page getStudentsByPage(int rows, int currentPage);
}
StudentServicelmpl:StudentService的实现
import com.xmcc.dao.StudentDao;
import com.xmcc.dao.impl.StudentDaolmpl;
import com.xmcc.entiy.Admin;
import com.xmcc.entiy.Page;
import com.xmcc.entiy.Student;
import com.xmcc.service.StudentService;
import java.util.ArrayList;
import java.util.List;
public class StudentServicelmpl implements StudentService {
StudentDao studentDao = new StudentDaolmpl() ;
@Override
//查询所有的学生
public List<Student> getStudent() {
return studentDao.getStudent();
}
@Override
public Page getStudentsByPage(int rows, int currentPage) {
//将第X页页面的数据展示出来
List<Student> students = studentDao.getStudentsByPage(rows,currentPage );
//获取所有的数据条数
int totalCount = studentDao.getTotalCount();
System.out.println(totalCount);
Page page = new Page(totalCount,rows,currentPage,students);
return page;
}
}
StudentDao:
package com.xmcc.dao;
import com.xmcc.entiy.Admin;
import com.xmcc.entiy.Student;
import java.util.ArrayList;
import java.util.List;
public interface StudentDao {
List<Student> getStudent();
List<Student> getStudentsByPage(int rows, int currentPage);
int getTotalCount();
}
StudentDaoimpl:
package com.xmcc.dao.impl;
import com.xmcc.dao.StudentDao;
import com.xmcc.entiy.Admin;
import com.xmcc.entiy.Student;
import com.xmcc.utils.JDBCutils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDaolmpl implements StudentDao {
@Override
public List<Student> getStudent() {
ArrayList<Student> students = new ArrayList<>();
//设置连接对象
Connection conn = null;
try {
//获取连接,连接数据库
conn = JDBCutils.getConnction();
//数据库执行语句
String sql = "select * from std";
//获取执行对象
PreparedStatement ps = conn.prepareStatement(sql);
//执行数据库语句,并将执行结果保存到resultSet中
ResultSet resultSet = ps.executeQuery();
//遍历resultSet
while (resultSet.next())
{
int id = resultSet.getInt(1);//resultSet.getInt()中可以直接写字段名,例如:resultSet.getInt(“id”)
String name = resultSet.getString(2);
int age = resultSet.getInt(3);
students.add(new Student(id,name,age));
}
JDBCutils.close(ps,conn ,resultSet );
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
@Override
public List<Student> getStudentsByPage(int rows, int currentPage) {
ArrayList<Student> students = new ArrayList<>();
Connection conn = null;
try {
conn = JDBCutils.getConnction();
String sql = "select * from std limit ?,?";
PreparedStatement ps = conn.prepareStatement(sql);
//设置第一个?处的值为(currentPage-1)*rows,这里主要是获取当前页是从数据库中第几条数据开始展示
ps.setInt(1,(currentPage-1)*rows );
//设置第二个?处的值为rows,这里主要是获取需要展示多少条数据
ps.setInt(2,rows );
ResultSet resultSet = ps.executeQuery();
while (resultSet.next())
{
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
int age = resultSet.getInt(3);
students.add(new Student(id,name,age));
}
JDBCutils.close(ps,conn ,resultSet );
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
@Override
public int getTotalCount() {
Connection conn = null;
int row = 0;
try {
conn = JDBCutils.getConnction();
String sql = "select * from std";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
//获得resultSet的最后一行
resultSet.last();
//获得当前resultSet的“下标”
row = resultSet.getRow();
JDBCutils.close(ps, conn, resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
return row;
}
}
数据库工具类:
package com.xmcc.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCutils {
//初始化数据源
private static DataSource dataSource;
static {
//读取流获取druid.properties
//JDBCUtilsConfig.class是获得当前对象所属的class对象
//getClassLoader()是取得该Class对象的类装载器
//getResourceAsStream(“database.properties”) 调用类加载器的方法加载 资源,返回的是字节流
//使用Properties类是为了可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象,然后通过getProperty方法用指定的键在此属性列表中搜索属性
InputStream in = JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
try {
properties.load(in);
//创建连接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭连接
public static Connection getConnction() throws SQLException {
return dataSource.getConnection();
}
public static DataSource getDataSource() {
return dataSource;
}
public static void close(Statement statement, Connection conn) throws SQLException {
statement.close();
conn.close();
}
public static void close(Statement statement, Connection conn, ResultSet resultSet) throws SQLException {
if(statement != null){
statement.close();
}
if(conn != null){
conn.close();
}
if(resultSet != null){
resultSet.close();
}
}
}
Page实体类:
package com.xmcc.entiy;
import java.util.List;
public class Page {
private int totalCount;//总条数 ---------数据库
private int totalPage;//总页数 ----------算出来的
private int rows;//每页显示行数 --------------自定义
private int currentPage;//当前页码 ---------前端
private List<Student> list; // 内容---------数据库
public Page() {
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
//计算有多少页,采用向上取整
int page = (int) Math.ceil(totalCount/(rows*1.0));
System.out.println("page="+page);
return page;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
public Page(int totalCount, int rows, int currentPage, List<Student> list) {
this.totalCount = totalCount;
this.rows = rows;
this.currentPage = currentPage;
this.list = list;
}
}
页面展示:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用户信息管理系统</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
td, th {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
//使用c:forEach遍历session中名为“pb”的session中list属性的值
<c:forEach items="${pb.list}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td><a class="btn btn-default btn-sm" href="/selectStudentByIdServlet?id=${stu.id}">修改</a> <a class="btn btn-default btn-sm" href="/deleteServlet?id=${stu.id}">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="8" align="center"><a class="btn btn-primary" href="add.html">添加联系人</a></td>
</tr>
</table>
<div>
<nav aria-label="Page navigation">
<ul class="pagination">
<li id="curremtPagelast">
<a class="curremtPagelast" href="/Servlet?curremtPagelast=${page}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${pb.totalPage}" var="i" step="1">
<li id="i${i}" class="page"><a class="page1" href="/Servlet?currentPage=${i}">${i}</a></li>
</c:forEach>
<li id="curremtPagenext">
<a class="curremtPagenext" href="/Servlet?curremtPagenext=${page}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 5px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>
</ul>
</nav>
</div>
</div>
<script>
$("#i${page}").addClass('active');
var page=${page};
console.log(page);
if(page===1){
console.log("last1")
$(".curremtPagelast").attr("disabled",true);
$(".curremtPagelast").css("pointer-events","none");
$("#curremtPagelast").addClass('disabled')
}else {
console.log("last2")
$(".curremtPagelast").attr("disabled",false);
$(".curremtPagelast").css("pointer-events","auto");
$("#curremtPagelast").removeClass('disabled')
}
var totalPage=${pb.totalPage}
if(page===totalPage){
console.log("next1")
$(".curremtPagenext").attr("disabled",true);
$(".curremtPagenext").css("pointer-events","none");
$("#curremtPagenext").addClass('disabled')
}else {
console.log("next2")
$(".curremtPagenext").attr("disabled",false);
$(".curremtPagenext").css("pointer-events","auto");
$("#curremtPagenext").removeClass('disabled')
}
</script>
</body>
</html>
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- obuygou.com 版权所有 赣ICP备2024042798号-5
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务