JavaWeb基础分页(一看就会)

时间:2025-03-31 20:25:08

首先我们要理清楚分页我们都需要哪些数据,是否需要工作类

public class Page<T> {
	// 当前页码
	private int pageIndex;
	
	// 每页数据量
	private int pageSize = 5;

	// 总页数
	private int pageCount;
	
	// 总数据量
	private int total;
	
	// 当前页数据
	private List<T> results;
}

理清我们所有的数据之后,就要开始考虑前台我们需要的首页,尾页,上一页,下一页

<a href="#?pageIndex=1">首页</a>

<a href="#?pageIndex=<%=() - 1 < 1 ? 1 : () - 1%>">上一页</a>
<a href="#?pageIndex=<%=() + 1 > () ? () : () + 1%>">下一页</a>

<a href="#?pageIndex=<%=()%>">尾页</a>&nbsp;&nbsp;
		当前第<%=()%>页,总共<%=()%>页 

当我们确定好之后就要开始考虑遍历我们的东西

<%
			Page<Student> pageInfo = (Page<Student>) ("page");
		
			List<Student> stu = ();
			%>

接收到之后我们就可以通过过JSTL进行遍历操作

后台代码

Servlet
/*
*正常接收
*/
Page<Student> page = ((pageIndex), pageSize);

Service
@Override
	public boolean updateStudent(String num, String phone, String address) {
		int count = (num,phone,address);
		if (count > 0) {
			return true;
		}
		return false;
	}
	@Override
	public Page<Student> getStudentByPage(int pageIndex, int pageSize) {
		
		Page<Student> page = new Page<Student>();
		//当前页
		(pageIndex);
		//每页数据量
		(pageSize);
		//总数据量
		int total = ();
		(total);
		//查询当前页数据 
		List<Student> results = (pageIndex,pageSize);
		(results);
		return page;
	}


Dao
@Override
	public int countStudents() {
		Connection conn = ();
		//查询到所有数据
		String sql = "select count(*) from student";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int count = 0;
		try {
			pstmt = (sql);
			rs = ();
			while (()) {
				count = (1);
			}
		} catch (SQLException e) {
			();
		} finally {
			(rs, pstmt, conn);
		}
		return count;
	}

	@Override
	public List<Student> getStudentByPage(int pageIndex, int pageSize) {
		Connection conn = ();
		String sql = "select * from student limit ?, ?";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Student> list = new ArrayList<Student>();
		Student sch = null;
		try {
			pstmt = (sql);
			(1, (pageIndex - 1) * pageSize);
			(2, pageSize);
			rs = ();
			while (()) {
				sch = new Student();
				(("student_num"));
				(("student_name"));
				(("student_sex"));
				(("student_age"));
				(("student_phone"));
				(("student_address"));
				sch.setClass1(("student_class"));
				(("student_room"));
				(sch);
			}
		} catch (SQLException e) {
			();
		} finally {
			(rs, pstmt, conn);
		}
		return list;
	}

如果还是看不懂 可以移步学生信息管理系统