Load Data While Scrolling Down Using Struts 2 and jQuery

Implement infinite scroll pagination to load database records as you scroll down using jQuery AJAX and Struts 2.

Infinite scrolling is a popular pattern for web applications. It allows you to load data progressively from a database and append the results to the page as the user scrolls. When no more records are available, a notice is displayed. You can configure how many records are fetched with each scroll request.

Follow the steps below to implement dynamic scroll-based loading in an Apache Struts 2 and jQuery application.

Step 1: Project Setup

Create a Dynamic Web Project in Eclipse and configure standard Struts 2 libraries along with the jQuery JavaScript library.

Step 2: Configure Client-Side Scroll Detection

In your main JSP page, attach an event listener to the scrolling element (or $(window)). When the user reaches near the bottom of the container, make an AJAX request to your Struts 2 action:

javascript
$(document).ready(function() {
    var loading = false;
    var page = 1;

    $('#contentBox').scroll(function() {
        if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 20) {
            if (!loading) {
                loading = true;
                $('#loadingMessage').show();
                $.ajax({
                    url: 'loadMoreData.action',
                    type: 'POST',
                    data: { pageNumber: page },
                    dataType: 'html',
                    success: function(response) {
                        if ($.trim(response)) {
                            $('#dataContainer').append(response);
                            page++;
                            loading = false;
                            $('#loadingMessage').hide();
                        } else {
                            $('#loadingMessage').text('No more data available.');
                        }
                    }
                });
            }
        }
    });
});

Step 3: Implement the Struts 2 Action

Create an action class LoadScrollDataAction.java that accepts the current page number, queries your DAO with pagination parameters (offset and limit), and puts the result list into the request context.

Java
package com.codewale.example.action;

import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class LoadScrollDataAction extends ActionSupport {
    private int pageNumber;
    private List<String> records;

    public String execute() {
        int pageSize = 10;
        int offset = (pageNumber - 1) * pageSize;
        records = CountryDAO.getCountries(offset, pageSize);
        return SUCCESS;
    }

    public int getPageNumber() { return pageNumber; }
    public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; }
    public List<String> getRecords() { return records; }
}

Step 4: Map Action in struts.xml

Configure the action mapping in struts.xml to render a partial JSP containing the newly appended items:

XML
<action name="loadMoreData" class="com.codewale.example.action.LoadScrollDataAction">
    <result name="success">/pages/dataFragment.jsp</result>
</action>

Step 5: Database Table Schema

Create the sample table and insert records into Oracle:

sql
drop table country;

create table country(
    countryname varchar2(50),
    countrycode varchar2(5)
);

insert into country(countryname, countrycode) values('Afghanistan', '93');
insert into country(countryname, countrycode) values('Albania', '355');
insert into country(countryname, countrycode) values('Algeria', '213');
insert into country(countryname, countrycode) values('American Samoa', '1684');
insert into country(countryname, countrycode) values('Andorra', '376');
insert into country(countryname, countrycode) values('Angola', '244');
insert into country(countryname, countrycode) values('Anguilla', '1264');
insert into country(countryname, countrycode) values('Antarctica', '672');
insert into country(countryname, countrycode) values('India', '91');
insert into country(countryname, countrycode) values('Indonesia', '62');

commit;

Run the application, move the cursor inside the content container, and scroll down to see the data load dynamically.

About Glenna Babshire29 Articles
Java & libraries writer. Writes the Java tutorials: the language from Java 21 on, encryption, configuration and the libraries around it.