JSP 웹사이트 개발: 페이지네이션 구현

이번 문서에서는 JSP를 사용한 웹사이트 개발에서 자주 사용되는 페이지네이션 기능을 구현하는 방법에 대해 설명합니다. 특히 데이터가 많은 경우 유용한 '바이두 스타일'의 페이지네이션을 예제로 다룹니다.

데이터 개수 조회 메소드:

public int getTotalCount() {
    int count = 0;
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        conn = DatabaseUtil.getConnection();
        String sql = "SELECT COUNT(*) FROM users";
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            count = rs.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DatabaseUtil.close(rs, pstmt, conn);
    }
    return count;
}

총 페이지 수 계산:

public int calculatePageCount(int recordsPerPage) {
    int totalRecords = this.getTotalCount();
    int totalPages = (int) Math.ceil((double) totalRecords / recordsPerPage);
    return totalPages;
}

현재 페이지에 표시할 데이터 가져오기:

public List<User> fetchPageData(int currentPage, int recordsPerPage) {
    List<User> userList = new ArrayList<>();
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        conn = DatabaseUtil.getConnection();
        String sql = "SELECT * FROM users LIMIT ?, ?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, (currentPage - 1) * recordsPerPage);
        pstmt.setInt(2, recordsPerPage);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setGender(rs.getInt("gender"));
            user.setAge(rs.getInt("age"));
            user.setHometown(rs.getString("hometown"));
            user.setSchool(rs.getString("school"));
            userList.add(user);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DatabaseUtil.close(rs, pstmt, conn);
    }
    return userList;
}

페이지네이션 구현 코드:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="com.example.jsp.User" %>
<%@ page import="com.example.jsp.UserManager" %>

<%
String contextPath = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/";
%>

<html>
<head>
    <base href="<%=basePath%>">
    <title>페이지네이션 예제</title>
</head>
<body>
<%
    int currentPage = 1;
    if (request.getParameter("page") != null) {
        currentPage = Integer.parseInt(request.getParameter("page"));
    }
    int recordsPerPage = 5;
    UserManager userManager = new UserManager();
    List<User> users = userManager.fetchPageData(currentPage, recordsPerPage);
    int totalRecords = userManager.getTotalCount();
    int totalPages = userManager.calculatePageCount(recordsPerPage);
%>
<center>
    <h1>페이지네이션 예제</h1>
    <hr/>
    | 번호 | ID | 이름 | 성별 | 나이 | 출생지 | 학교 |
|---|---|---|---|---|---|---|
| &lt;%=users.indexOf(user) + 1%&gt; | &lt;%=user.getId()%&gt; | &lt;%=user.getName()%&gt; | &lt;%=user.getGender() == 1 ? "남자" : "여자"%&gt; | &lt;%=user.getAge()%&gt; | &lt;%=user.getHometown()%&gt; | &lt;%=user.getSchool()%&gt; |
| &lt;% if (currentPage &gt; 1) { %&gt; [처음](PaginationExample.jsp?page=1) &lt;% } %&gt; &lt;% if (currentPage &gt; 1) { %&gt; [이전](<PaginationExample.jsp?page=<%=currentPage - 1%>>) &lt;% } %&gt; &lt;% for (int i = 1; i &lt;= totalPages; i++) { if (i == currentPage) { %&gt; <span>&lt;%=i%&gt;</span> &lt;% } else { %&gt; [&lt;%=i%&gt;](PaginationExample.jsp?page=<%=i%>) &lt;% }} %&gt; &lt;% if (currentPage &lt; totalPages) { %&gt; [다음](<PaginationExample.jsp?page=<%=currentPage + 1%>>) &lt;% } %&gt; &lt;% if (currentPage &lt; totalPages) { %&gt; [마지막](PaginationExample.jsp?page=<%=totalPages%>) &lt;% } %&gt; |
</center>
</body>
</html>

태그: JSP java MySQL 페이지네이션

7월 29일 06:57에 게시됨