JSP+SQL SERVER实现分页

原理是:根据用户的点击获得curPage的数目,然后从而从数据库中读出本页应该显示的数据。

代码:

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <%@page import="java.sql.*" %> <%@page import="bean.SQLHelper" %> <%@page import="java.util.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>Insert title here</title> </head> <body> <% int curPage=1;//当前的页码 int maxPage;//总的页数 int maxRows=0;//总的行数 int rowsPerPage=2;//每页的行数 Connection conn=SQLHelper.getConnection(); try { String sql="select count(*) from user1"; Statement stm=conn.createStatement(); ResultSet rs=stm.executeQuery(sql); while(rs.next()) { maxRows=rs.getInt(1); } conn.close(); } catch(Exception ex) { ex.printStackTrace(); } //计算应该 的页数 if(maxRows%rowsPerPage==0) { maxPage=maxRows/rowsPerPage; } else { maxPage=maxRows/rowsPerPage+1; } String temp=request.getParameter("ding"); if(temp==null) { temp="1"; } if(temp!="") curPage=Integer.parseInt(temp); Connection conn1=SQLHelper.getConnection(); ArrayList<Object[]> list=new ArrayList<Object[]>(); try { Statement stm=conn1.createStatement(); String sql=null; sql="select top "+rowsPerPage+" * from user1 where username not in(select top "+rowsPerPage*(curPage-1)+"username from user1)"; ResultSet rs=stm.executeQuery(sql); while(rs.next()) { Object[] obj=new Object[2]; obj[0]=rs.getString("username"); obj[1]=rs.getString("passwrd"); list.add(obj); } conn.close(); } catch(Exception ex) { ex.printStackTrace(); } %> <table width="580" align="center"> <tr> <th>用户名</th> <th>密码</th> </tr> <%for(int i=0;i<list.size();i++) {%> <%Object[] obj1=list.get(i);%> <%out.println("<tr><td>"+obj1[0].toString()+"</td>"); %> <%out.println("<td>"+obj1[1].toString()+"</td></tr>"); %> <%} %> </table> <table width="580" align="center"> <tr> <td>总页数:<%=maxPage %></td> <td>当前的页数:<%=curPage %></td> <td> <%if(curPage>1){%> <a href="index.jsp?ding=<%=curPage-1%>">上一页</a> <%} %> <%if(curPage>0&&curPage<maxPage){ %> <% int temp2=curPage+1; String stemp2=String.valueOf(temp2); %> <a href="index.jsp?ding=<%=curPage+1%>">下一页</a> <%} %> </td> </tr> </table> </body> </html>

你可能感兴趣的:(sql,jsp,exception,String,server,object,import)