日期:2014-05-16  浏览次数:20402 次

jsp实现分页功能

功能:把数据库中的某张表在jsp页面中进行分页显示。

代码:?????

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%@ page import="java.sql.*" %>
<%
   request.setCharacterEncoding("gbk");
   String strPageNo=request.getParameter("pageNo");
   int pageNo;
   if(strPageNo==null||strPageNo.equals(""))
   {
          pageNo=1;
   
   }else{
         try{
        pageNo=Integer.parseInt(strPageNo.trim());
        }
        catch(NumberFormatException e)
        {
             pageNo=1;
        }
      if(pageNo<=0)
      {
        pageNo=1;
      }
   }
     
     
     int pageSize=3;
     Class.forName("com.mysql.jdbc.Driver");
     String url="jdbc:mysql://localhost:3306/bbs?user=root&password=12345678";
     Connection conn=DriverManager.getConnection(url);   
     Statement stmt=conn.createStatement();
     String sql="select count(*) from article where pid=0";
     ResultSet rs=stmt.executeQuery(sql);
     rs.next();
     int totalnumber=rs.getInt(1);//总页数
     stmt.close();
     rs.close();
     int totalpages=totalnumber%pageSize==0?totalnumber/pageSize:totalnumber/pageSize+1;//需要多少页进行显示
     if(pageNo>totalpages)pageNo=totalpages;//如果当前页码大于总页数,那么将页码置为最大页数
     int startpos=(pageNo-1)*pageSize;//当前页的第一条记录在数据库中的位置
     Statement stmtsearch=conn.createStatement();
     String sqlsearch="select * from article where pid=0 limit "+startpos+","+totalpages;
     ResultSet rssearch=stmtsearch.executeQuery(sqlsearch);
                    
     
        
     
 %>
<!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>
<center>
<a href="post.jsp">发表帖子</a>
 <table border="1" width="80%">
       <%
         while(rssearch.next()){
        %>
         <tr>
          <td>
            <a href="showfurther.jsp?id=<%=rssearch.getInt("id")%>"><%=rssearch.getString("title")%></a>
          </td>
         </tr>
       <%
       }
        %>      
</table>
<a href="showflat.jsp?pageNo=1">首页</a>
<a href="showflat.jsp?pageNo=<%=pageNo-1%>">上一页</a>
<a href="showflat.jsp?pageNo=<%=pageNo+1%>">下一页</a>
<a href="showflat.jsp?pageNo=<%=totalpages%>">最后一页</a>
<form action="showflat.jsp" name="form1">
        <select name="pageNo"  onchange="document.form1.submit()">
             <%
              for(int i=1;i<=totalpages;i++){
              %>  
               <option value=<%=i%> <%=(pageNo==i)?"selected":""%>>第<%=i %>页 </option>
             <%
             }
              %>
         </select>
</form>
<form action="showflat.jsp" name=form2>
      <input type="text" name="pageNo" value=<%=pageNo%>>
      <input type="submit" value="go">
</form>
</center>
    <%
      rssearch.close();
      stmtsearch.close();
      conn.close(); 
     %>      
</body>
</html>

?

????????????