利用纯JSP技术实现分页效果

来源:互联网 发布:有win本 还要mac 编辑:程序博客网 时间:2024/06/03 23:59

分页技术的思路:

1.连接数据库

2.获取总记录数

3.定义每页显示数

4.计算总页数

5.当前页传值与接值

6.确定当前页的范围:首页之后,尾页之前

7.确定每页的第一条记录在数据表的位置

8.查询

9.循环显示每页的信息

 

下面以查询学生基本信息为例,数据库采用MSSQLServer数据库,展现分页效果。

数据库students,数据表stu,字段有:学号(stu_id)、姓名(stu_name)、性别(stu_sex)、年龄(stu_age)

详细代码如下:

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
 <title>纯JSP实现学生信息分页</title>
</head>

<body>
<table align="center" cellpadding="3" cellspacing="1" bgcolor="#0099FF" width="700">
 <%
  int totalCount = 0;//定义总记录数
  int pageSize = 2;//定义每页显示数
  int pageCount = 0;//定义总页数
  int currentPage = 1;//定义当前显示页
  try{
   String sql = "select count(*) from stu";//定义获取总记录数的SQL命令
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//加载驱动
   Connection con = DriverManager.getConnection("jdbc:odbc:sun","sa","");//连接数据库
   Statement st = con.createStatement(1004,1007);//创建执行SQL命令的对象
   ResultSet rs = st.executeQuery(sql);//获取结果
   boolean b = rs.next();//将游标移动到第一行
   if(b)
   {
    totalCount = rs.getInt(1);//如果有值,获取总记录数
    if(totalCount>0)
    {
     pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;//计算总页数
     String sp2 = request.getParameter("sp");//接收当前页传值
     if(sp2!=null)
     {
      try{
       currentPage = Integer.parseInt(sp2);//将接收的值赋给当前页
      }catch(NumberFormatException nfe){
       currentPage = 1;
      }
     }

    //确定当前页的范围在首页之后,尾页之前
     if(currentPage < 1)
     {
      currentPage = 1;
     }
     if(currentPage > pageCount)
     {
      currentPage = pageCount;
     }

     sql = "select * from stu";  //定义查询所有的SQL命令
     rs = st.executeQuery(sql);//执行查询操作
     int position = (currentPage-1)*pageSize+1;//确定每页的第一条记录在数据表的位置
     rs.absolute(position);//定位

    //循环显示
     for(int i = 0 ; i < pageSize ; i ++)
     {

     //当游标没有到达最后一行之后时循环显示
      if(rs.isAfterLast()==false)
      {
       int id = rs.getInt(1);
       String name = rs.getString(2);
       String sex = rs.getString(3);
       int age = rs.getInt(4);
 %>
       <tr bgcolor="#FFFFFF">
        <td><%=id%></td>
        <td><%=name%></td>
        <td><%=sex%></td>
        <td><%=age%></td>
       </tr>
 <%
       rs.next();
      }
     }
 %>
      <tr bgcolor="#FFFFFF">
       <td colspan="4">
        [<a href="?sp=1">首页</a>]
        [<a href="?sp=<%=currentPage-1%>">前页</a>]
        [<a href="?sp=<%=currentPage+1%>">后页</a>]
        [<a href="?sp=<%=pageCount%>">尾页</a>]
       </td>
      </tr>
 <%
    }
   }
  }catch(ClassNotFoundException cnfe){
   out.print(cnfe);
  }catch(SQLException se){
   out.print(se);
  }
 %>
</table>

</body>
</html>

 

 

原创粉丝点击