java web 开发 分页功能 mysql数据库

list.jsp:

<div class="right_content">
  <h2 class="bulletin_h2">系统公告</h2>
  <div class="bulletin_content">
   <ul>
    <c:forEach items="${notices}" var="notice">
     <li><em>>></em> <a href="getnecontent?id=${notice.id}">${notice.title}</a>
      <span>删除</span>
      <span>编辑</span>
      <span>${notice.pubtime }</span>
     </li>
    </c:forEach>
   </ul>
    <c:if test="${currentPage != 1}">
     <a href="noticelist?page=${currentPage - 1}">Previous</a>
    </c:if>
    <c:forEach begin="1" end="${noOfPages}" var="i">
     <c:choose>
      <c:when test="${currentPage eq i}">
       <td>${i}</td>
      </c:when>
      <c:otherwise>
       <td><a href="noticelist?page=${i}">${i}</a>
       </td>
      </c:otherwise>
     </c:choose>
    </c:forEach>
    <c:if test="${currentPage lt noOfPages}">
     <td><a href="noticelist?page=${currentPage + 1}">Next</a>
     </td>
    </c:if>
  </div>
 </div>

list.java:

public ArrayList<Notice> getNotices(int offset,int recordsPerPage){
  ResultSet rs=null;
  PreparedStatement ps =null;
  ArrayList<Notice> notices = new ArrayList<Notice>();
  Connection conn = JdbcUtils.getConnection();
  String sql = "select SQL_CALC_FOUND_ROWS id,title,content,person,filepath,pubtime from notice order by id desc limit ?,? ";
  try {
   ps = conn.prepareStatement(sql);
   ps.setInt(1, offset);
   ps.setInt(2, recordsPerPage);
   rs = ps.executeQuery();
   while(rs.next()){
    Notice notice = new Notice();
    notice.setId(rs.getInt("id"));
    notice.setTitle(rs.getString("title"));
    notice.setContent(rs.getString("content"));
    notice.setPerson(rs.getString("person"));
    notice.setFilepath(rs.getString("filepath"));
    notice.setPubtime(rs.getString("pubtime"));
    notices.add(notice);
   }
   rs.close();
   rs = ps.executeQuery("SELECT FOUND_ROWS()");
   if(rs.next())
               this.noOfRecords = rs.getInt(1);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return notices;
 }

servlet:

  //处理乱码
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html; charset=gbk"); 
  
  int page = 1;
        int recordsPerPage = 10;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
       
  NoticeDAO nd = new NoticeDAOImpl();
  ArrayList<Notice> notices = nd.getNotices((page-1)*recordsPerPage,recordsPerPage);
  int noOfRecords = nd.getNoOfRecords();
  int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
  
  request.setAttribute("notices", notices);
  request.setAttribute("noOfPages", noOfPages);
  request.setAttribute("currentPage", page);
  request.getRequestDispatcher("noticelist.jsp").forward(request, response);

参考资料:http://www.cnblogs.com/super119/archive/2011/01/13/1934997.html

QQ群:127402101,进群请修改备注。

posted @ 2013-04-10 12:22  11hxian.com  阅读(348)  评论(0编辑  收藏  举报