jsp分页

<%!
    int pataSize=5;// 每页多少数据
    int totalCount =0; //数据共多少
    int pageCount = 0; ///数据共有多少页
    int index=1; //index开始

  
    void getCount(int count)   //放入的一共的数据 totalCount 
   {
   pageCount = (totalCount%pataSize==0)?(totalCount/pataSize):(totalCount/pataSize+1);    //三元表达,判断有数据一共多少页
   };
  
   %>
   <% 
   if(request.getParameter("index")!=null)   //传过来的index判断是不是空
   {
   index=Integer.parseInt(request.getParameter("index"));  //获取index
   }
   if(index>=1){    // 大于1的index
  index=index-1;
   }else
{
  index=0;    // 首页
}
  if(index<=13)  //小于13的index
  {
  index=index+1;
  }else
  {
  index=14;   //尾页
  }
   
   Context ctx = new InitialContext();   //连接池
   DataSource ds =(DataSource) ctx.lookup("java:comp/env
bc/news");
   Connection con =ds.getConnection();
   PreparedStatement ps =con.prepareStatement("SELECT count(1) FROM news");    //看看一共有多少数据
   ResultSet rs = ps.executeQuery();    //遍历出来
   if(rs.next())      //开始判断下一个有没有
   {
   totalCount=rs.getInt("count(1)");
   }
    PreparedStatement pss =con.prepareStatement("SELECT `ntitle` FROM news LIMIT ?,?");   //sql语句
    pss.setInt(1,(index-1)*pataSize);               //传入数据
    pss.setInt(2, pataSize);                //传入数据
   rs = pss.executeQuery();
   while(rs.next())          //遍历出来
   {
   out.print(rs.getString(1)+"<br>");
   }
   getCount(totalCount);    //放入的一共的数据 totalCount 
   for(int i =0;i<pageCount;i++)  //遍历循环这个页数
   {
   %>
   <a href='index.jsp?index=<%=(i+1)%>'><%out.print((i+1)); %></a>
   <%
   }
   %>
   <br><a href='index.jsp?index=<%=1%>'><%out.print("首页"); %></a>    //index 为1的时候是首页
  <a href='index.jsp?index=<%=index-1%>'><%out.print("上一页"); %></a>  //index 为-1的时候是上一页
  <a href='index.jsp?index=<%=index+1%>'><%out.print("下一页"); %></a>  //index 为+1的时候是下一页
  <a href='index.jsp?index=<%=14%>'><%out.print("尾页"); %></a>      //index 为14的时候是尾页
   <%

//关闭数据库
    try{
    rs.close();
    }catch(SQLException s){
    s.printStackTrace();
    }
    try{
    ps.close();
    }catch(SQLException s){
    s.printStackTrace();
    }
    try{
    con.close();
    }catch(SQLException s){
    s.printStackTrace();
    }
    %>

posted @ 2018-01-11 21:32  MensaoThe_Villain  阅读(120)  评论(0编辑  收藏  举报