Implementing Pagination for Large Datasets in Java Web Applications

Introduction

Handling large datasets in web applications can be challenging, especially when presenting them to users in a manageable way. Pagination is a common solution that allows users to navigate through large amounts of data in smaller, more digestible pages. This article will guide you through implementing pagination in a Java web application using a JSP page and Servlet, similar to how you would manage large datasets in an ASP.NET WebForms GridView.

Setting Up the Data Source

First, let's assume you have a method that fetches a large dataset from the database. For demonstration purposes, we'll simulate this with a List of objects.

import java.util.ArrayList;
import java.util.List;
public class DataService {
    public List<String> getData() {
        List<String> data = new ArrayList<>();
        for (int i = 1; i <= 2000; i++) {
            data.add("Name " + i);
        }
        return data;
    }
}

Implementing Pagination in the Servlet

In the servlet, we will handle the logic for fetching a subset of data based on the current page number and page size.

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/data")
public class DataServlet extends HttpServlet {
    private static final int PAGE_SIZE = 10;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DataService dataService = new DataService();
        List<String> allData = dataService.getData();
        // Determine the current page number
        int page = 1;
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        // Calculate the start and end index
        int startIndex = (page - 1) * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, allData.size());
        // Get the subset of data for the current page
        List<String> data = allData.subList(startIndex, endIndex);
        // Set attributes for the JSP
        request.setAttribute("data", data);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", (int) Math.ceil((double) allData.size() / PAGE_SIZE));
        // Forward to JSP
        request.getRequestDispatcher("/data.jsp").forward(request, response);
    }
}

Creating the JSP Page

In the JSP page, you’ll loop through the data and display it in a table. Additionally, you'll include pagination controls to navigate between pages.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Data Pagination Example</title>
</head>
<body>
<h2>Data Pagination Example</h2>
<table border="1">
    <tr>
        <th>Index</th>
        <th>Data</th>
    </tr>
    <c:forEach var="item" items="${data}" varStatus="status">
        <tr>
            <td>${status.index + 1}</td>
            <td>${item}</td>
        </tr>
    </c:forEach>
</table>
<!-- Pagination controls -->
<div>
    <c:if test="${currentPage > 1}">
        <a href="data?page=1">First</a>
        <a href="data?page=${currentPage - 1}">Previous</a>
    </c:if>

    <c:if test="${currentPage < totalPages}">
        <a href="data?page=${currentPage + 1}">Next</a>
        <a href="data?page=${totalPages}">Last</a>
    </c:if>
</div>

</body>
</html>

Example. Real-World Use in a Project

Imagine you have an application that manages user records stored in a database. You want to display these records in pages of 10 users each. With the provided code structure, you can easily implement a paginated view of user records, allowing users to navigate through pages efficiently.

@WebServlet("/users")
public class UserServlet extends HttpServlet {
    private static final int PAGE_SIZE = 10;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService = new UserService();
        List<User> allUsers = userService.getAllUsers();
        int page = 1;
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        int startIndex = (page - 1) * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, allUsers.size());
        List<User> users = allUsers.subList(startIndex, endIndex);
        request.setAttribute("users", users);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", (int) Math.ceil((double) allUsers.size() / PAGE_SIZE));
        request.getRequestDispatcher("/users.jsp").forward(request, response);
    }
}

Conclusion

Implementing pagination is essential for handling large datasets in web applications. This approach prevents overwhelming users with too much data at once and improves the application's performance. The provided Java example demonstrates a basic yet effective way to implement pagination in a web application using servlets and JSP. This can be easily adapted for various data types and scenarios, ensuring a scalable and user-friendly interface.


Similar Articles