What's the correct way to paginate (particularly with JQuery and Jersey)

Viewed 1298

Just want to run by my method of pagination with Jersey on the server side, and JQuery on the client.

On server (assuming the user has just requested /rest/users?page=1):

    // Hardcoded the page number here, but it would be page-1, page+1
    String prevLink = uriInfo.getRequestUri() + "?page=0";
    String nextLink = uriInfo.getRequestUri() + "?page=2";
    String linkHeader = String.format(LINK_HEADER_TMPL, prevLink,  nextLink);
    return List<User> currentPageResults;

This gives me the following header in the response:

Link: <http://localhost:8880/rest/users?page=0>; rel="prev", <http://localhost:8880/rest/users?page=2>; rel="next"

On client:

 var xhr = $.getJSON("rest/users", function(allData) {
        var links = (xhr.getResponseHeader("link")).split(',');
        var relLinks = [];
        $.each(links, function(index, value) {
            var parts = value.split(';');
            var url = parts[0].replace(/^.*<(.*)>.*$/m, '$1');
            var rel = parts[1].replace(/^.*"(.*)".*$/m, '$1');
            relLinks[rel] = url;
        });

        alert(relLinks['prev']);

The alert gives me the right thing, and is what I'd use to generate my page links:

http://localhost:8880/rest/users?page=0

So questions:

  1. Is my link header formatted correctly? Parsing the link header on the client side seems a little convulted.
  2. Is this a correct/accepted way of doing this? I looked at the Jersey response filter, but that requires adding Jersey-specific annotations on the model class, which I didn't want to do.
  3. What about total available pages? Is there a standardised way of giving that in the info? If I had the page total, I could presumably drop the rel links altogether, and just generate them client side? Would that be correct?

Incidentally, how did the whole format of link headers come about? The form "url; rel=name,url;rel=name" seems a bit weird to me.

EDIT: Found this https://www.rfc-editor.org/rfc/rfc5988#section-6.2, which specifies 'standard' relation names

1 Answers
Related