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

Spring Controller无法接收分页请求中的page参数问题

解决Spring MVC中@RequestParam接收page参数始终为默认值的问题

问题场景

Controller方法定义:

@GetMapping 
public Page<Routine> getAll(
    @RequestParam(required = false) String type,
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size){

    Pageable paging = PageRequest.of(page, size);
    return routineRepository.findByTypeAndSharedIsTrue(type, paging);
}

Repository接口:

public interface RoutineRepository extends MongoRepository<Routine, String>{
    Page<Routine> findByTypeAndSharedIsTrue(String type, Pageable pageable);
}

请求curl http://localhost:1235/api/routines?type=Calisthenics时page取默认值0正常,但请求curl http://localhost:1235/api/routines?type=Calisthenics&page=1时,page始终为0,无法接收传入值。

排查与解决方法

1. 检查请求参数的传递有效性

终端中&符号可能被解析为后台执行标记,导致page=1未被正确传递。尝试:

  • 用引号包裹URL:
    curl "http://localhost:1235/api/routines?type=Calisthenics&page=1"
    
  • 或转义&:
    curl http://localhost:1235/api/routines?type=Calisthenics\&page=1
    

2. 解决Spring Data Pageable自动注入冲突

Spring Data默认会自动注入Pageable对象,可能和手动定义的page、size参数冲突,导致手动参数无法被正确绑定。

方案A:直接使用自动注入的Pageable

修改Controller方法,移除手动定义的page和size,直接用Pageable参数:

@GetMapping 
public Page<Routine> getAll(
    @RequestParam(required = false) String type,
    Pageable pageable){
    return routineRepository.findByTypeAndSharedIsTrue(type, pageable);
}

此时请求参数page和size会被自动封装为Pageable,若要设置size默认值为10,在配置文件中添加:

spring.data.web.pageable.default-page-size=10

方案B:禁用自动注入的Pageable

在配置类上添加注解,关闭自动注入:

@EnableSpringDataWebSupport(pageableDetectionStrategy = PageableDetectionStrategy.NONE)
@Configuration
public class WebConfig {
    // 其他配置
}

这样手动定义的page、size参数就能正常接收请求值。

3. 排查参数绑定异常

在Controller方法中添加BindingResult查看绑定错误,同时打印参数值:

@GetMapping 
public Page<Routine> getAll(
    @RequestParam(required = false) String type,
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size,
    BindingResult bindingResult){

    if(bindingResult.hasErrors()){
        bindingResult.getAllErrors().forEach(err -> System.err.println(err.getDefaultMessage()));
    }
    System.out.println("实际接收的page值:" + page);
    Pageable paging = PageRequest.of(page, size);
    return routineRepository.findByTypeAndSharedIsTrue(type, paging);
}

若控制台打印page仍为0,说明请求参数未正确传递;若有绑定错误,根据提示调整参数类型(如传入非数字字符串导致int绑定失败)。


内容的提问来源于stack exchange,提问作者Luis Baz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:18:36