You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot WebClient:传递Pageable参数及接收Page返回对象方法

解决Spring Boot中WebClient调用带Pageable的REST接口问题

一、传递Pageable参数

Pageable在GET请求中通过查询参数传递(对应page、size、sort等参数),WebClient可通过两种方式构建请求:

方式1:用UriComponentsBuilder构建完整参数

Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("page", String.valueOf(pageable.getPageNumber()));
params.add("size", String.valueOf(pageable.getPageSize()));
// 处理多字段排序,格式为"属性名,排序方向"
pageable.getSort().forEach(order -> 
    params.add("sort", String.format("%s,%s", order.getProperty(), order.getDirection()))
);

// 后续拼接接收逻辑

方式2:直接拼接简单参数

如果排序逻辑简单,可直接在URI中拼接参数:

Pageable pageable = PageRequest.of(0, 10);

// 后续拼接接收逻辑

二、正确接收Page类型返回值

你之前的代码bodyToMono(Page.class)报错,核心原因是泛型类型擦除:Spring无法识别Page内部的泛型参数,导致反序列化失败。

解决方法是使用ParameterizedTypeReference指定完整泛型类型:

// 替换原有的bodyToMono(Page.class)
.bodyToMono(new ParameterizedTypeReference<Page<Object>>() {})

如果返回的是自定义实体(比如User),只需替换泛型参数:

.bodyToMono(new ParameterizedTypeReference<Page<User>>() {})

完整可运行代码

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;

public class WebClientPageDemo {
    private final WebClient webClient;

    public WebClientPageDemo(WebClient webClient) {
        this.webClient = webClient;
    }

    public Page<Object> callDemoApi() {
        // 构建分页参数
        Pageable pageable = PageRequest.of(0, 10, Sort.by("createTime").descending());

        // 组装查询参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("page", String.valueOf(pageable.getPageNumber()));
        params.add("size", String.valueOf(pageable.getPageSize()));
        pageable.getSort().forEach(order -> 
            params.add("sort", String.format("%s,%s", order.getProperty(), order.getDirection()))
        );

        // 调用接口并接收分页结果
        return webClient.get()
                .uri(uriBuilder -> uriBuilder.path("/demo")
                        .queryParams(params)
                        .build())
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Page<Object>>() {})
                .block();
    }
}

额外注意事项

  • 若后端返回的Page包含自定义扩展字段,需确保泛型类型能匹配这些字段,否则会反序列化失败。
  • 非测试场景下尽量避免使用block(),响应式项目中建议用flatMap等操作符处理Mono<Page<T>>。

内容的提问来源于stack exchange,提问作者Tarun Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 01:51:11