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,進群請修改備忘。 |