我正在使用Spring Boot(v2.2.2. RELEASE)Spring Data Mongo Spring REST Spring HATEOAS示例。在此示例中,如果消费者发送分页max-page-size=200超过200,则我需要显示错误消息说最大允许大小为200。
我经历了许多链接,如:spring.data.rest. max-page-size似乎不起作用?,但没有一个解决方案对我有用。
我正在使用HATEOAS实现并使用PagedResourcesAssembler和表示ModelAssemblerSupport。
有什么指点吗?
@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;
}
}
注意:我还使用了spring.data. web.page.max-page-size=200
在application.properties
文件中。
我能够用下面的代码解决这个问题,这工作得很好。
@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);
}
}