分页是JavaEE学习中我们常用的一个知识,在起初我的学习中,当时有许多不理解,从jsp的分页,再到servlet,然后hibernate中的分页,逐渐的熟悉理解这个知识。由于是从头复习,这里使用jsp+MySQL实现分页,实际开发中并不建议使用,代码可读性太差,不符合MVC模式,这里只是做一个了解。
通知分页要使用MySQL的select * from where Student limit x,y。
自己写的JDBC工具类:
private static Connection conn=null;
private static PreparedStatement ps=null;
private static ResultSet rs=null;
static{
String URL="jdbc:mysql://localhost:3306/chenlong2";
String user="root";
String pass="123456";
String driver="com.mysql.jdbc.Driver";
try {
Class.forName(driver);
conn=DriverManager.getConnection(URL,user,pass);
System.out.println("连接成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 分页
*/
public static ResultSet pageSize(String sql) throws SQLException{
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
return rs;
}
index.jsp
<body>
<%
int pageNow=1,pageSize=2,pageCount=0,rowCount=3;
String s=request.getParameter("pageNow");
if(s!=null){
pageNow=Integer.parseInt(s);}
else
pageNow=1;
pageCount=(rowCount-1)/pageSize+1;
ResultSet rs=JDBCUtil.pageSize("select * from thephonebook limit "+pageSize*(pageNow-1)+","+pageSize+"");
%>
This is my JSP page. <br>
<table>
<tr><td>姓名</td><td>电话</td><td>地址</td></tr>
<%
while(rs.next()){
%>
<tr><td><%=rs.getString(1)%></td><td><%=rs.getString(2)%></td><td><%=rs.getString(3)%></td></tr>
<%
}
%>
</table>
<%
for(int i=1;i<=pageCount;i++){
%>
<a href="index.jsp?pageNow=<%=i%>"><%=i %></a>
<%
}
%>
<form action="index.jsp" name="form1" method="post">
<input type="text" name="number">
<input type="button" onclick="pageCheck()" value="onclicl">
</form>
</body>
</html>
这里就实现了简单的数据分页显示