JavaWeb基础分页(一看就会)

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

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

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

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

首页

上一页
下一页

尾页  
		当前第<%=pageInfo.getPageIndex()%>页,总共<%=pageInfo.getPageCount()%>页 

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

<%
			Page pageInfo = (Page) request.getAttribute("page");
		
			List stu = pageInfo.getResults();
			%>

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

后台代码

Servlet
/*
*正常接收
*/
Page page = studentService.getStudentByPage(Integer.parseInt(pageIndex), pageSize);

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


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

	@Override
	public List getStudentByPage(int pageIndex, int pageSize) {
		Connection conn = this.getConnection();
		String sql = "select * from student limit ?, ?";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List list = new ArrayList();
		Student sch = null;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, (pageIndex - 1) * pageSize);
			pstmt.setInt(2, pageSize);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				sch = new Student();
				sch.setNum(rs.getString("student_num"));
				sch.setName(rs.getString("student_name"));
				sch.setSex(rs.getString("student_sex"));
				sch.setAge(rs.getInt("student_age"));
				sch.setPhone(rs.getString("student_phone"));
				sch.setAddress(rs.getString("student_address"));
				sch.setClass1(rs.getString("student_class"));
				sch.setRoom(rs.getString("student_room"));
				list.add(sch);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeConnection(rs, pstmt, conn);
		}
		return list;
	}

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

你可能感兴趣的:(linq,蓝桥杯,c#)