JSP分页功能实现案例:从基础到应用的全面解析
想要实现基于jsp的分页功能:
需要从数据库中获取数据,并在前端页面中分页展示
- 基于JDBC访问MySQL数据库,获取数据
- 基于JSP处理数据并展示
本质上是JSP的一种开发模式(即JSP+JavaBean)
第一步:创建JavaWeb项目,配置pom.xml文件
项目结构
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>fenye_9_18_rumen</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>fenye_9_18_rumen Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--文件上传,这里暂时用不到-->
<!-- <dependency>-->
<!-- <groupId>smartupload</groupId>-->
<!-- <artifactId>smartupload</artifactId>-->
<!-- <version>1.0</version>-->
<!-- <scope>system</scope>-->
<!-- <systemPath>D:/maven/maven-3.9.9/repository/smartuplaod/smartupload/1.0/smartupload.jar</systemPath>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>fenye</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.14.v20161028</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8080</port>
<path>/my_maven_pro</path>
<uriEncoding>UTF-8</uriEncoding>
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
第二步:创建数据库表和对应的实体类
t_user表
创建用户表,包含用户id,用户名和用户密码字段,并且预先存储一些数据
表结构如下
User.java
引入了lombok注解,自动生成getter/setter方法和有参无参构造
package entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private Integer userId;
private String userName;
private String password;
}
第三步:导入JDBC工具类DBUtil和分页工具类PageUtil
DBUtil
工具类中的数据库名以及用户名和密码是自己本地的数据库中的数据库名和MySQL的账号和密码(注意甄别)
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBUtil {
private final static String DRIVER="com.mysql.cj.jdbc.Driver";
private final static String URL="jdbc:mysql://localhost:3306/csx_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
private final static String DBNAME="root";
private final static String DBPASS="root";
public static Connection getConn(){
Connection conn=null;
try {
Class.forName(DRIVER);
conn= DriverManager.getConnection(URL,DBNAME,DBPASS);
}catch (Exception e){
e.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn, Statement st, ResultSet rs){
try {
if (rs!=null){
rs.close();
}
if (st!=null){
st.close();
}
if (conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
PageUtil
目的是获取,当前的分页页数
package util;
public class PageUtil {
public static final int PAGE_SIZE=3;//每页显示条数
public static int getTotalPages(int count,int pageSize){
return count%pageSize==0?count/pageSize:count/pageSize+1;
}
}
第四步:分析功能实现需要的SQL支持,书写DAO
UserDao
package dao;
import entity.User;
import java.util.List;
public interface UserDao {
/**
* 查看用户总条数
* @return
*/
int selectUsersCount();
/**
* 分页查询用户列表
* @param pageIndex 当前页
* @param pageSize 每页显示的条数
* @return
*/
List<User> selectUserListByPage(int pageIndex, int pageSize);
}
UserDaoImpl
package dao.impl;
import dao.UserDao;
import entity.User;
import util.DBUtil;
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 UserDaoImpl extends DBUtil implements UserDao {
private Connection conn=null;
private PreparedStatement pstmt=null;
private ResultSet rs=null;
/**
* 查看用户总条数
*
* @return
*/
@Override
public int selectUsersCount() {
int count=0;
try{
//继承工具类中的方法,获取数据库连接
conn=getConn();
String sql="select count(user_id) from t_user";
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
if (rs.next()){
//返回单行单列数据
count=rs.getInt(1);
}
}catch (SQLException e){
e.printStackTrace();
}
//返回count
return count;
}
/**
* 分页查询用户列表
*
* @param pageIndex 当前页
* @param pageSize 每页显示的条数
* @return
*/
@Override
public List<User> selectUserListByPage(int pageIndex, int pageSize) {
List<User> list =new ArrayList<>();
try{
conn=getConn();
String sql="select * from t_user order by user_id desc limit ?,?";
pstmt=conn.prepareStatement(sql);
//分页查询
pstmt.setInt(1,pageSize*(pageIndex-1));
pstmt.setInt(2,pageSize);
rs=pstmt.executeQuery();
while (rs.next()){
User user =new User(rs.getInt(1),rs.getString(2),rs.getString(3));
list.add(user);
}
}catch (SQLException e){
e.printStackTrace();
}
return list;
}
}
第五步:创建处理后端数据并展示的jsp
结构
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
</web-app>
userList.jsp
<%@ page import="dao.UserDao" %>
<%@ page import="dao.impl.UserDaoImpl" %>
<%@ page import="util.PageUtil" %>
<%@ page import="java.util.List" %>
<%@ page import="entity.User" %><%--
Created by IntelliJ IDEA.
User: 21038
Date: 2024/9/18
Time: 10:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>分页查询</title>
</head>
<body>
<table border="1px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<%
String currentPage=request.getParameter("pageIndex");
if (currentPage==null){
currentPage="1";
}
int pageIndex = Integer.parseInt(currentPage);
UserDao userDao =new UserDaoImpl();
int count = userDao.selectUsersCount();
//总页数
int totalPages= PageUtil.getTotalPages(count,PageUtil.PAGE_SIZE);
List<User> list= userDao.selectUserListByPage(pageIndex,PageUtil.PAGE_SIZE);
for (User u:list){
%>
<tr>
<td><%=u.getUserId()%></td>
<td><%=u.getUserName()%></td>
<td>
<a href="">修改</a>
<a href="">删除</a>
</td>
</tr>
<%
}
%>
<tr>
<td colspan="3">
<a href="userList.jsp?pageIndex=1">首页</a>
<a href="userList.jsp?pageIndex=<%=pageIndex-1%>">上一页</a>
<a href="userList.jsp?pageIndex=<%=pageIndex+1%>">下一页</a>
<a href="userList.jsp?pageIndex=<%=totalPages%>">最后一页</a>
</td>
</tr>
</table>
</body>
</html>
此时的功能是存在一些问题的,比如当我们在首页点击前一页或在最后一页点击下一页都会出现数据异常,但是这里主要展示如何完成分页功能,暂不处理,后续会在servlet实现分页功能中完善。
第六步:运行测试
启动项目,并在浏览器的地址栏输入:
只实现了分页功能,操作部分的修改和删除等功能暂时未完成
这里的数据来自数据库
总结
基于JSP+JavaBean开发模式,完成了简单的分页功能,可以存在一些问题,我会在servlet实现分页功能的博客中全部解决,这里只是演示如何开发一个分页的功能实现。