简体   繁体   中英

Datatables AJAX Data Source and Custom Pagination actions

I am using Datatables for building the table for my data.

I am passing JSON response from Server side [Java] to JSP and using Datatables js to build the tables in JSP using the same data.

If I pass 100 records, Datatables automatically provides facility to paginate and scroll through the results. But in my case, I always get only 20 records and when I user click on next page, I should call the localServlet to fetch fresh JSON response for next 20records.

So how do I configure Datatable so that whenever pagination function is used, call the AJAX resource and fetch the data and paint it.

There is a sample at http://datatables.net/release-datatables/examples/data_sources/server_side.html

however the code is in PHP. But having a look at it you will see that there request parameters it uses are iDisplayStart and iDisplayLength

You will have to reimplement this in your server side java.

Below is some code I have used (using Stripes)

    Long count = (Long) getContext().getRequest().getSession(true).getAttribute("xbcount");
    if (count == null) {
        count = histDao.getCount();
        getContext().getRequest().getSession(true).setAttribute("xbcount", count);
    }

    DataTableRes res = new DataTableRes (getsEcho(), count, count);

    int rowStartIdxAndCount[] = {getiDisplayStart(), getiDisplayLength()};

    List<HistoryUint> list = histDao.findAll(rowStartIdxAndCount);

And the DAO

public List<HistoryUint> findAll(final int... rowStartIdxAndCount) {
    EntityManagerHelper.log("finding all HistoryUint instances",
            Level.INFO, null);
    try {
        final String queryString = "select model from HistoryUint model";
        Query query = getEntityManager().createQuery(queryString);
        if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
            int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
            if (rowStartIdx > 0) {
                query.setFirstResult(rowStartIdx);
            }

            if (rowStartIdxAndCount.length > 1) {
                int rowCount = Math.max(0, rowStartIdxAndCount[1]);
                if (rowCount > 0) {
                    query.setMaxResults(rowCount);
                }
            }
        }
        return query.getResultList();
    } catch (RuntimeException re) {
        EntityManagerHelper.log("find all failed", Level.SEVERE, re);
        throw re;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM