Spring RestTemplate with paginated API

前端 未结 7 2062
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 17:22

Our REST APIs are returning results in Pages. Here is an example of one Controller

@RequestMapping(value = \"/search\", method = RequestMethod.GET, produces          


        
相关标签:
7条回答
  • 2020-11-27 17:49

    There is no need in implementing a Page. You just have to use a PagedResources<T> as a type in your ParameterizedTypeReference.

    So if your service returns response similar to (objects are removed for brevity):

    {
        "_embedded": {
            "events": [
                {...},
                {...},
                {...},
                {...},
                {...}
            ]
        },
        "_links": {
            "first": {...},
             "self": {...},
             "next": {...},
             "last": {...}
        },
        "page": {
            "size": 5,
            "totalElements": 30,
            "totalPages": 6,
            "number": 0
        }
    }
    

    And the objects you care are of type Event then you should execute the request like:

    ResponseEntity<PagedResources<Event>> eventsResponse = restTemplate.exchange(uriBuilder.build(true).toUri(),
                    HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Event>>() {});
    

    If you get hold of the resources like:

    PagedResources<Event> eventsResources = eventsResponse.getBody();
    

    you will be able to access the page metadata (what you get in the "page" section), the links ("_links" section) and the content:

    Collection<Event> eventsCollection = eventsResources.getContent();
    
    0 讨论(0)
提交回复
热议问题