基於「表示層-控制層-DAO層-數據庫」經典分層架構,實現通用分頁查詢功能。歡迎指正優化建議。
totalPages = (totalRecords + pageSize - 1) / pageSizeLIMIT offset, pageSize,offset = (pageNo - 1) * pageSizeJDBCUtilspublic class JDBCUtils {
private static final String URL = "jdbc:mysql://localhost:3306/book";
private static final String USER = "root";
private static final String PASS = "1234";
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
public void close(Connection conn, PreparedStatement ps, ResultSet rs) {
closeQuietly(rs);
closeQuietly(ps);
closeQuietly(conn);
}
// closeQuietly 省略...
}
UserDaopublic class UserDao {
private static final int PAGE_SIZE = 5;
private JDBCUtils jdbc = new JDBCUtils();
// 總頁數
public int getTotalPages() {
String sql = "SELECT COUNT(*) FROM books";
try (Connection conn = jdbc.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
int total = rs.getInt(1);
return (total + PAGE_SIZE - 1) / PAGE_SIZE;
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// 分頁查詢
public List<User> listByPage(int pageNo) {
List<User> list = new ArrayList<>();
String sql = "SELECT * FROM books ORDER BY id LIMIT ?, ?";
int offset = (pageNo - 1) * PAGE_SIZE;
try (Connection conn = jdbc.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, offset);
ps.setInt(2, PAGE_SIZE);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setNumber(rs.getString("number"));
list.add(u);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Userpublic class User {
private int id;
private String name;
private String number;
// Getter/Setter 省略...
}
ListUserServlet@WebServlet("/ListUser")
public class ListUserServlet extends HttpServlet {
private UserDao userDao = new UserDao();
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int pageNo = 1;
String param = req.getParameter("pageNos");
if (param != null) pageNo = Integer.parseInt(param);
List<User> list = userDao.listByPage(pageNo);
int totalPages = userDao.getTotalPages();
req.setAttribute("listss", list);
req.setAttribute("recordCount", totalPages);
req.setAttribute("pageNos", pageNo);
req.getRequestDispatcher("userlist.jsp").forward(req, resp);
}
}
userlist.jsp<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<table align="center" border="1" cellpadding="5">
<tr><th>書號</th><th>書名</th><th>庫存量</th></tr>
<c:forEach items="${listss}" var="book">
<tr>
<td>${book.id}</td>
<td>${book.name}</td>
<td>${book.number}</td>
</tr>
</c:forEach>
</table>
<c:if test="${pageNos > 1}">
<a href="ListUser?pageNos=1">首頁</a>
<a href="ListUser?pageNos=${pageNos-1}">上一頁</a>
</c:if>
<c:if test="${pageNos < recordCount}">
<a href="ListUser?pageNos=${pageNos+1}">下一頁</a>
<a href="ListUser?pageNos=${recordCount}">末頁</a>
</c:if>
<form action="ListUser" method="get">
共 ${recordCount} 頁
<input type="text" name="pageNos" value="${pageNos}" size="3"> 頁
<input type="submit" value="跳轉">
</form>
