JSP中的简单分页

<%@ page language="java" pageEncoding="UTF-8"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.SQLException"%>

<html>

     <head>

        </head>

          <body>   

          <ul>    

      <%    

         Connection con = null;     //连接对象     

         PreparedStatement pst = null;     //命令处理对象     

         ResultSet res = null;     //结果集     

         int pageindex = 1;//当前页数    

         int pagesize = 4;//每一页页码    

         int pagecount = 1;//总页数    

         try {     

             if (request.getParameter("px") != null) {      //判断请求的参数不为空 第一次加载的时候给值为1       

               pageindex = Integer.parseInt(request.getParameter("px"));      

            }

             else {

                   pageindex = 1;

               }      

             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");     

             con = DriverManager.getConnection(        "jdbc:sqlserver://127.0.0.1:1434;databaseName=BBSDB",        "sa", "beansa123");                String sql = "select top " + pagesize + " * from Topic";      sql += " where TId not in(select top " + (pageindex - 1)        * pagesize + " Tid from Topic)";        //分页数据      

            String psql = "select count(*) as counts  from Topic";      //查询所有条数的

            SQL      pst = con.prepareStatement(psql);     

              res = pst.executeQuery();      //     

              if (res.next()) {      //判断取到下一条      

               int count = (Integer) res.getObject(1);       //得出总条数     

                 if (count % pagesize == 0) {      

                  pagecount = count / pagesize;      

               }

               else {      

                  pagecount = count / pagesize + 1;      

               }     

            }      //处理分页SQL语句    

            pst = con.prepareStatement(sql);    

            res = pst.executeQuery();    

            while (res.next()) {   

      %>   

         <li>     

          <%=res.getInt(1)%>

        </li>   

      <%    

               }    

             } catch (SQLException exp) {    

                  throw exp;    

              } finally {     

                 if (res != null)      

                 res.close();     

                 if (pst != null)      

                 pst.close();     

                 if (con != null)     

                   con.close();     

              }    

       %>

        </ul>  

         <a href="index.jsp?px=1">首页</a>   

         <a href="index.jsp?px=<%=pageindex - 1 > 0 ? pageindex - 1 : 1%>">上一页</a>   

           <a    href="index.jsp?px=<%=pageindex + 1 < pagecount ? pageindex + 1      : pagecount%>">下一页</a>   

         <a href="index.jsp?px=<%=pagecount%>">最后一页</a>  

   </body>

</html>

posted @ 2013-08-11 18:51  @追&梦ぅかづ  阅读(194)  评论(0编辑  收藏  举报