带有分页 API 的 Spring RestTemplate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34647303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring RestTemplate with paginated API
提问by turgos
Our REST APIs are returning results in Pages. Here is an example of one Controller
我们的 REST API 在页面中返回结果。这是一个控制器的示例
@RequestMapping(value = "/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
@ResponseStatus(HttpStatus.OK)
public Page<MyObject> findAll(Pageable pageable) {
...
}
Is there an easy way to consume that API with RestTemplate?
有没有一种简单的方法可以通过 RestTemplate 使用该 API?
if we do
如果我们这样做
ParameterizedTypeReference<Page<MyObject>> responseType = new ParameterizedTypeReference<Page<MyObject>>() { };
ResponseEntity<Page<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType);
List<MyObject> searchResult = result.getBody().getContent();
it throws an exception
它抛出异常
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of org.springframework.data.domain.Page,
problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information at [Source: java.io.PushbackInputStream@3be1e1f2; line: 1, column: 1]; nested exception is com.fasterxml.Hymanson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Page, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
Thank you in advance
先感谢您
采纳答案by turgos
Changed the code reading the Rest API response as;
将读取 Rest API 响应的代码更改为;
ParameterizedTypeReference<RestResponsePage<MyObject>> responseType = new ParameterizedTypeReference<RestResponsePage<MyObject>>() { };
ResponseEntity<RestResponsePage<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType);
List<MyObject> searchResult = result.getBody().getContent();
And here is the class I created for RestResponsePage
这是我为 RestResponsePage 创建的类
package com.basf.gb.cube.seq.vaadinui.util;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
public class RestResponsePage<T> extends PageImpl<T>{
private static final long serialVersionUID = 3248189030448292002L;
public RestResponsePage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
// TODO Auto-generated constructor stub
}
public RestResponsePage(List<T> content) {
super(content);
// TODO Auto-generated constructor stub
}
/* PageImpl does not have an empty constructor and this was causing an issue for RestTemplate to cast the Rest API response
* back to Page.
*/
public RestResponsePage() {
super(new ArrayList<T>());
}
}
回答by ???
When migrating from Spring Boot 1.x to 2.0, changed the code reading the Rest API response as
从 Spring Boot 1.x 迁移到 2.0 时,将读取 Rest API 响应的代码更改为
import com.fasterxml.Hymanson.annotation.JsonCreator;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.fasterxml.Hymanson.databind.JsonNode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public class RestPageImpl<T> extends PageImpl<T>{
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestPageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number,
@JsonProperty("size") int size,
@JsonProperty("totalElements") Long totalElements,
@JsonProperty("pageable") JsonNode pageable,
@JsonProperty("last") boolean last,
@JsonProperty("totalPages") int totalPages,
@JsonProperty("sort") JsonNode sort,
@JsonProperty("first") boolean first,
@JsonProperty("numberOfElements") int numberOfElements) {
super(content, PageRequest.of(number, size), totalElements);
}
public RestPageImpl(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestPageImpl(List<T> content) {
super(content);
}
public RestPageImpl() {
super(new ArrayList<>());
}
}
回答by Stephen
Expanding on above, but without the need to implement every property.
在上面进行扩展,但不需要实现每个属性。
import com.fasterxml.Hymanson.annotation.JsonCreator;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public class RestPageImpl<T> extends PageImpl<T>{
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestPageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int page,
@JsonProperty("size") int size,
@JsonProperty("totalElements") long total) {
super(content, new PageRequest(page, size), total);
}
public RestPageImpl(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestPageImpl(List<T> content) {
super(content);
}
public RestPageImpl() {
super(new ArrayList());
}
}
回答by Vladimir Mitev
There is no need in implementing a Page
. You just have to use a PagedResources<T>
as a type in your ParameterizedTypeReference
.
没有必要实施Page
. 你只需要PagedResources<T>
在你的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:
并且您关心的对象属于类型,Event
那么您应该执行如下请求:
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:
您将能够访问页面元数据(您在该"page"
部分中获得的内容)、链接("_links"
部分)和内容:
Collection<Event> eventsCollection = eventsResources.getContent();
回答by Loren
I had to make a small change so it would ignore the unknown property of empty that seems to have been recently introduced.
我不得不做一个小的改变,这样它就会忽略最近引入的空的未知属性。
import com.fasterxml.Hymanson.annotation.JsonCreator;
import com.fasterxml.Hymanson.annotation.JsonIgnoreProperties;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.fasterxml.Hymanson.databind.JsonNode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestResponsePage<T> extends PageImpl<T> {
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestResponsePage(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number,
@JsonProperty("size") int size,
@JsonProperty("totalElements") Long totalElements,
@JsonProperty("pageable") JsonNode pageable,
@JsonProperty("last") boolean last,
@JsonProperty("totalPages") int totalPages,
@JsonProperty("sort") JsonNode sort,
@JsonProperty("first") boolean first,
@JsonProperty("numberOfElements") int numberOfElements) {
super(content, PageRequest.of(number, size), totalElements);
}
public RestResponsePage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestResponsePage(List<T> content) {
super(content);
}
public RestResponsePage() {
super(new ArrayList<>());
}
}
回答by Danijel Sudar
Solution in Kotlin
Kotlin 中的解决方案
import com.fasterxml.Hymanson.annotation.JsonCreator
import com.fasterxml.Hymanson.annotation.JsonProperty
import com.fasterxml.Hymanson.databind.JsonNode
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import java.util.ArrayList
class RestResponsePage<T> : PageImpl<T> {
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
constructor(@JsonProperty("content") content: List<T>,
@JsonProperty("number") number: Int,
@JsonProperty("size") size: Int,
@JsonProperty("totalElements") totalElements: Long?,
@JsonProperty("pageable") pageable: JsonNode,
@JsonProperty("last") last: Boolean,
@JsonProperty("totalPages") totalPages: Int,
@JsonProperty("sort") sort: JsonNode,
@JsonProperty("first") first: Boolean,
@JsonProperty("numberOfElements") numberOfElements: Int) : super(content, PageRequest.of(number, size), totalElements!!) {
}
constructor(content: List<T>, pageable: Pageable, total: Long) : super(content, pageable, total) {}
constructor(content: List<T>) : super(content) {}
constructor() : super(ArrayList<T>()) {}
}
and request
并要求
var response: ResponseEntity<*> = restTemplate.getForEntity<RestResponsePage<SomeObject>>(url)
Solution in Java
Java中的解决方案
import com.fasterxml.Hymanson.annotation.JsonCreator;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.fasterxml.Hymanson.databind.JsonNode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public class RestResponsePage<T> extends PageImpl<T> {
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestResponsePage(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number,
@JsonProperty("size") int size,
@JsonProperty("totalElements") Long totalElements,
@JsonProperty("pageable") JsonNode pageable,
@JsonProperty("last") boolean last,
@JsonProperty("totalPages") int totalPages,
@JsonProperty("sort") JsonNode sort,
@JsonProperty("first") boolean first,
@JsonProperty("numberOfElements") int numberOfElements) {
super(content, PageRequest.of(number, size), totalElements);
}
public RestResponsePage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestResponsePage(List<T> content) {
super(content);
}
public RestResponsePage() {
super(new ArrayList<>());
}
}
回答by Simon Flandergan
The solution posted didn't work for me, because the total elements were not set correctly. I implemented the Page with a delegate pattern, which worked for me. Here's the working code:
发布的解决方案对我不起作用,因为总元素设置不正确。我使用委托模式实现了页面,这对我有用。这是工作代码:
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RestPage<T> implements Page<T> {
private PageImpl<T> pageDelegate = new PageImpl<>(new ArrayList<>(0));
public List<T> getContent() {
return pageDelegate.getContent();
}
public int getNumber() {
return pageDelegate.getNumber();
}
public int getNumberOfElements() {
return pageDelegate.getNumberOfElements();
}
public int getSize() {
return pageDelegate.getSize();
}
public Sort getSort() {
return pageDelegate.getSort();
}
public long getTotalElements() {
return pageDelegate.getTotalElements();
}
public int getTotalPages() {
return pageDelegate.getTotalPages();
}
public boolean hasContent() {
return pageDelegate.hasContent();
}
public boolean hasNext() {
return pageDelegate.hasNext();
}
public boolean hasPrevious() {
return pageDelegate.hasPrevious();
}
public boolean isFirst() {
return pageDelegate.isFirst();
}
public boolean isLast() {
return pageDelegate.isLast();
}
public Iterator<T> iterator() {
return pageDelegate.iterator();
}
public <S> Page<S> map(Converter<? super T, ? extends S> converter) {
return pageDelegate.map(converter);
}
public Pageable nextPageable() {
return pageDelegate.nextPageable();
}
public Pageable previousPageable() {
return pageDelegate.previousPageable();
}
public void setContent(List<T> content) {
pageDelegate = new PageImpl<>(content, null, getTotalElements());
}
public void setTotalElements(int totalElements) {
pageDelegate = new PageImpl<>(getContent(), null, totalElements);
}
public String toString() {
return pageDelegate.toString();
}
}