Spring Boot v2.2.2.RELEASE 当分页大小超过预期时抛出错误

Spring Boot v2.2.2.RELEASE throw error when Pagination Size more than anticipated

我正在使用 Spring 引导 (v2.2.2.RELEASE) + Spring 数据 Mongo + Spring REST + Spring HATEOAS 示例。在此示例中,如果消费者发送的 Pagination max-page-size=200 大于 200,那么我需要显示错误消息,说明最大允许大小为 200。

我浏览了很多链接,例如:spring.data.rest.max-page-size does not seem to work?,但是 none 的解决方案对我来说仍然有效。

我正在使用 HATEOAS 实现并使用 PagedResourcesAssembler 和 RepresentationModelAssemblerSupport。

有什么指点吗?

@Configuration
public class RespositoryConfiguration extends RepositoryRestMvcConfiguration {
    @Value("${paging.default.pageSize}")
    private int size;

    @Value("${paging.default.page}")
    private int page;

    public RespositoryConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    @Override
    @Bean
    public HateoasPageableHandlerMethodArgumentResolver pageableResolver() {
        HateoasPageableHandlerMethodArgumentResolver resolver = super.pageableResolver();
        resolver.setPageParameterName("page");
        resolver.setSizeParameterName("size");
        resolver.setOneIndexedParameters(false);
        resolver.setFallbackPageable(PageRequest.of(0, 25));
        resolver.setMaxPageSize(200);
        return resolver;
    }
}

注意:我也在 application.properties 文件中使用了 spring.data.web.pageable.max-page-size=200

我能够用下面的代码解决这个问题,而且效果很好。

@Configuration
public class WebConfig implements WebMvcConfigurer {
    ...
    ....

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver() {

            @Override
            public Pageable resolveArgument(MethodParameter methodParameter,
                    @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                    @Nullable WebDataBinderFactory binderFactory) {
                Pageable p = super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);

                if(p.getPageSize() > Integer.parseInt(env.getProperty("max.pagination.size"))) {
                    throw new MandatoryResourceException(env.getProperty("max.pagination.size.error.message"),
                            env.getProperty("max.pagination.size.error.code"));
                }

                return p;
            }
        };

        resolvers.add(resolver);
        WebMvcConfigurer.super.addArgumentResolvers(resolvers);
    }
}