可选的 Spring 分页 [英] Optional pagination with Spring
问题描述
我对 Java 和 Spring 还很陌生.
I am pretty new to java and spring.
我想要实现的是带有分页和排序功能的 api 端点 /tickets
.我做到了,而且有效.但如果查询参数中未指定 size
和 page
,我想做的是返回所有票证的普通列表,因此在 FE 中我可以使用该列表在选择框中.
What I want to implement is api endpoint /tickets
with pagination and sorting. I made it and it works. But also what I would like to do is to return plain list of all tickets if size
and page
are not specified in the query params, so in FE I can use that list in selectbox.
我试图做的是在服务外观上实现 getTickets
并返回所有票证的列表.但是我没有找到如何检查是否设置了 Pageable 的方法,因为它总是返回默认值 (size=20, page=0)
What I have tried to do is to implement getTickets
on service facade and return list of all tickets. But I didn't find a way how to check if Pageable is set as it always returns default values (size=20, page=0)
//控制器
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<TicketListItemResponseModel>> getTickets(Pageable pageable) {
logger.info("> getTickets");
Page<TicketListItemResponseModel> tickets = ticketServiceFacade.getTickets(pageable);
logger.info("< getTickets");
return new ResponseEntity<>(tickets, HttpStatus.OK);
}
//TicketServiceFacade
//TicketServiceFacade
public Page<TicketListItemResponseModel> getTickets(Pageable pageable) {
Page<Ticket> tickets = ticketService.findAll(pageable);
return tickets.map(new ConverterFromPagesToListItem());
}
public List<TicketListItemResponseModel> getTickets() {
List<Ticket> tickets = ticketService.findAll();
return tickets.stream()
.map(t -> modelMapper.map(t, TicketListItemResponseModel.class))
.collect(Collectors.toList());
}
也许我做错了?
推荐答案
如果你像这样构建你的控制器方法,你可以通过检查请求参数来管理是否要实现分页:
If you build out your controller method like so, you can manage whether or not you want to implement paging by checking the request params:
@Override
public ResponseEntity<Page<TicketListItemResponseModel>> getTickets(
@RequestParam(value = "page", defaultValue = "0", required = false) int page,
@RequestParam(value = "count", defaultValue = "10", required = false) int size,
@RequestParam(value = "order", defaultValue = "ASC", required = false) Sort.Direction direction,
@RequestParam(value = "sort", defaultValue = "name", required = false) String sortProperty) {
// here you would check your request params and decide whether or not to do paging and then return what you need to return
}
如果您需要构建一个 PageRequest 以传递给您的服务方法,您可以像这样手动执行:
If you need to build a PageRequest to pass into your service method, you can do so manually like so:
new PageRequest(page, size, new Sort(direction, sortProperty));
这篇关于可选的 Spring 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!