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

Spring Boot(Kotlin)如何自定义Pageable分页接口的返回响应?

自定义分页响应字段的实现方案

针对Spring Data Page返回冗余字段的问题,有两种常用的实现方案,可根据需求选择:

方案一:自定义分页响应DTO(推荐,完全可控)

自己定义只包含所需字段的分页类,将Spring Data的Page对象转换为自定义类返回,完全掌控返回字段的增删。

步骤1:创建自定义分页响应类

// 根据需求定义需要的字段,比如保留总条数、总页数、每页大小、当前页、数据列表
data class CustomPageResponse<T>(
    val totalElements: Long,
    val totalPages: Int,
    val pageSize: Int,
    val currentPage: Int,
    val content: List<T>,
    // 可按需新增字段,比如是否有下一页
    val hasNext: Boolean
)

步骤2:修改接口返回类型并转换数据

@GetMapping
fun getAll(
    @RequestParam(required = false) nameCourse: String?,
    pagination: Pageable
): CustomPageResponse<ResponseTopicDto> {
    val pageResult = service.getAll(nameCourse, pagination)
    return CustomPageResponse(
        totalElements = pageResult.totalElements,
        totalPages = pageResult.totalPages,
        pageSize = pageResult.size,
        currentPage = pageResult.number,
        content = pageResult.content,
        hasNext = pageResult.number < pageResult.totalPages - 1
    )
}

方案二:使用Jackson Mixin过滤冗余字段

如果不想修改接口返回类型,可以通过Jackson的Mixin机制,直接忽略Page类中的冗余字段。

步骤1:创建Page类的Mixin

import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.data.domain.Page

abstract class PageMixin<T> {
    // 忽略不需要的字段,按需调整
    @JsonIgnore
    abstract fun getSort(): Any?

    @JsonIgnore
    abstract fun isFirst(): Boolean

    @JsonIgnore
    abstract fun isLast(): Boolean

    @JsonIgnore
    abstract fun getNumberOfElements(): Int

    @JsonIgnore
    abstract fun getPageable(): Any?

    @JsonIgnore
    abstract fun isEmpty(): Boolean
}

步骤2:注册Mixin到ObjectMapper

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.data.domain.Page

@Configuration
class JacksonConfig {
    @Bean
    fun objectMapper(): ObjectMapper {
        val mapper = ObjectMapper()
        // 为Spring Data的Page类绑定Mixin
        mapper.addMixIn(Page::class.java, PageMixin::class.java)
        return mapper
    }
}

这样修改后,原接口返回的Page对象会自动过滤掉标记为@JsonIgnore的字段,无需改动接口代码。


内容的提问来源于stack exchange,提问作者Iago Antunes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 23:15:06