我对java和spring很陌生。
我要实现的是/tickets带有分页和排序功能的api端点。我做到了,而且有效。但也是我想做的是,如果返回所有门票的普通列表size,并page没有在查询参数指定的,所以在FE我可以使用选择框该列表。
/tickets
size
page
我试图做的是getTickets在服务外观上实现并返回所有票证列表。但是我没有找到一种方法来检查是否设置了Pageable,因为它总是返回默认值(size = 20,page = 0)
getTickets
//控制器
@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
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()); }
也许我做错了吗?
如果像这样构建控制器方法,则可以通过检查请求参数来管理是否要实现分页:
@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传递到服务方法中,则可以手动进行操作,如下所示:
new PageRequest(page, size, new Sort(direction, sortProperty));