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.*" %> Insert title here <% 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 list=new ArrayList(); 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(); } %>

<%for(int i=0;i <%Object[] obj1=list.get(i);%> <%out.println(""); %> <%out.println(""); %> <%} %>
用户名 密码
"+obj1[0].toString()+""+obj1[1].toString()+"
总页数:<%=maxPage %> 当前的页数:<%=curPage %> <%if(curPage>1){%> 上一页 <%} %> <%if(curPage>0&&curPage <% int temp2=curPage+1; String stemp2=String.valueOf(temp2); %> 下一页 <%} %>

你可能感兴趣的:(JSP/SERVLET)