可选的Spring分页

时间:2016-11-15 21:26:14

标签: java spring spring-boot spring-data

我是java和spring的新手。

我想要实现的是具有分页和排序的api端点/tickets。我做了它,它的工作原理。但是我想要做的是在查询参数中未指定sizepage时返回所有票证的简单列表,因此在FE中我可以在selectbox中使用该列表。

我尝试做的是在服务外观上实现getTickets并返回所有故障单的列表。但我找不到如何检查Pageable是否设置的方法,因为它始终返回默认值(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

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());
}

也许我完全错了?

1 个答案:

答案 0 :(得分:5)

如果你像这样构建你的控制器方法,你可以通过检查请求参数来管理你是否想要实现分页:

@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));