推荐使用Spring Data的Pageable和Page实现REST分页,自动绑定page、size、sort参数,返回含元数据的标准化JSON响应,并支持Specification动态查询与安全校验。

Spring Boot 中基于 REST API 的分页查询,推荐直接使用 Spring Data 提供的 Pageable 和 Page,它天然支持标准 URL 参数(如 page、size、sort),无需手动解析,也便于前后端统一约定。
URL 参数自动绑定 Pageable
Spring MVC 能自动将请求参数映射为 Pageable 对象,只要控制器方法参数声明为 Pageable,并确保参数名符合默认规范:
-
page:页码(从 0 开始,默认 0) -
size:每页条数(默认 20) -
sort:排序字段,格式如name,asc或age,desc;支持多个,如?sort=name,asc&sort=age,desc
示例接口:
@GetMapping("/users")
public ResponseEntity<page>> getUsers(Pageable pageable) {
Page<user> page = userRepository.findAll(pageable);
return ResponseEntity.ok(page);
}</user></page>
调用示例:GET /users?page=1&size=10&sort=createdAt,desc → 第 2 页(0 起始)、每页 10 条、按创建时间降序。
自定义 Pageable 参数名(可选)
若需兼容已有前端习惯(如用 pageNum、pageSize),可通过 @PageableDefault 或配置 PageableHandlerMethodArgumentResolver 实现。更简单的方式是显式接收参数再构建 Pageable:
@GetMapping("/users")
public ResponseEntity<page>> getUsers(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam(defaultValue = "id,desc") String sort) {
<pre class="brush:php;toolbar:false;">Sort.Direction direction = Sort.Direction.DESC;
String property = "id";
if (sort.contains(",")) {
String[] parts = sort.split(",", 2);
property = parts[0];
direction = "asc".equalsIgnoreCase(parts[1]) ? Sort.Direction.ASC : Sort.Direction.DESC;
}
Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(direction, property));
return ResponseEntity.ok(userRepository.findAll(pageable));}
注意:此时页码建议按 1 起始(更符合前端直觉),内部转为 0 起始传给 PageRequest.of()。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
响应结构标准化(返回 Page 的 JSON)
Page 对象序列化后自带分页元数据,例如:
{
"content": [ /* 用户列表 */ ],
"pageable": { "sort": { "sorted": true, ... }, "offset": 10, "pageNumber": 1, "pageSize": 10, ... },
"last": false,
"totalPages": 5,
"totalElements": 47,
"first": false,
"numberOfElements": 10,
"empty": false
}
该结构已包含全部分页上下文,前端可直接使用 totalElements、totalPages、first/last 等字段做 UI 控制。如需精简响应,可封装为自定义 DTO(如 PagedResponse<t></t>),只保留必要字段:data、currentPage、totalItems、totalPages、hasNext、hasPrevious。
配合 Specification 或自定义查询时的注意事项
若需动态条件分页(如带搜索),推荐使用 JpaSpecificationExecutor:
public interface UserRepository extends JpaRepository<user long>, JpaSpecificationExecutor<user> { }</user></user>
然后在 service 中组合条件:
Specification<user> spec = Specification.where(null);
if (StringUtils.hasText(name)) {
spec = spec.and((root, query, cb) -> cb.like(root.get("name"), "%" + name + "%"));
}
Page<user> result = userRepository.findAll(spec, pageable);</user></user>
注意:Spring Data 会自动为 Specification 查询添加分页 COUNT 和 LIMIT,无需额外处理。
不复杂但容易忽略的是参数校验和默认值控制——比如限制最大 size 防止恶意拉取全表,可在配置中全局设置:spring.data.web.pageable.max-page-size=100,或在代码中拦截校验。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










