org.springframework.data.domain.Pageable返回首页编号0

时间:2018-12-24 04:37:48

标签: spring spring-boot spring-data

使用org.springframework.data.domain.Pageable。 我想从1开始分页号码。 我看到了相同的帖子,确实做到了,但它们在我的应用中不起作用。

Get spring boot pagination number starts from 1 instead of 0

Spring Data Rest - Configure pagination

build.gradle

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.data:spring-data-rest-webmvc'
}

config

import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.data.web.config.PageableHandlerMethodArgumentResolverCustomizer;
import org.springframework.stereotype.Component;

@Component
public class CustomConfig implements PageableHandlerMethodArgumentResolverCustomizer {
    @Override
    public void customize(PageableHandlerMethodArgumentResolver pr) {
        pr.setOneIndexedParameters(true);
    }
}

控制器

@GetMapping("/")
public Integer index(Pageable pageable) {
    return pageable.getPageNumber();
}

结果

% curl 'localhost:8080/'
0
% curl 'localhost:8080/?page=1'
0
% curl 'localhost:8080/?page=2'
1

我想做

% curl 'localhost:8080/'
1
% curl 'localhost:8080/?page=1'
1
% curl 'localhost:8080/?page=2'
2

1 个答案:

答案 0 :(得分:1)

尝试像下面这样用WebMvcConfigurerAdapter进行配置,而不是直接实现PageableHandlerMethodArgumentResolverCustomizer

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setOneIndexedParameters(true);
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }
}

如果您使用的是Spring Boot 2.X,则可以从WebMvcConfigurerAdapter切换到如下所示的应用程序属性:

# DATA WEB (SpringDataWebProperties)
spring.data.web.pageable.default-page-size=20 # Default page size.
spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted.
spring.data.web.pageable.one-indexed-parameters=true # Whether to expose and assume 1-based page number indexes.
spring.data.web.pageable.page-parameter=page # Page index parameter name.
spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters.
spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties.
spring.data.web.pageable.size-parameter=size # Page size parameter name.
spring.data.web.sort.sort-parameter=sort # Sort parameter name.