自定义 PageUtils 分页
719人浏览 / 0人评论
PageUtils.java
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
public class PageUtils<T> {
private List<T> content;
private long totalElements;
private int totalPages;
private PageableUtils pageable;
public PageUtils() {
}
public PageUtils(Pageable pageable, Page<T> page) {
this.totalElements = page == null ? 0 : page.getTotalElements();
this.pageable = new PageableUtils(pageable);
this.totalPages = page.getTotalPages();
this.content = page.getContent();
}
public PageUtils(Pageable pageable, List<T> content) {
this.totalElements = content == null ? 0 : content.size();
this.pageable = new PageableUtils(pageable);
this.totalPages = totalElements % pageable.getPageSize() != 0 ? (int)totalElements / pageable.getPageSize() + 1: (int)totalElements / pageable.getPageSize();
this.content = pagination(pageable, content);
}
public PageUtils(Pageable pageable, List<T> content, long total) {
this.totalElements = total;
this.pageable = new PageableUtils(pageable);
this.totalPages = totalElements % pageable.getPageSize() != 0 ? (int)totalElements / pageable.getPageSize() + 1: (int)totalElements / pageable.getPageSize();
this.content = pagination(pageable, content);
}
public List<T> pagination(Pageable pageable, List<T> content) {
if (CollectionUtils.isNotEmpty(content)) {
int fromIndex = (int) pageable.getOffset();
int pageSize = pageable.getPageSize();
if (fromIndex > content.size()) {
return new ArrayList<T>();
}
int toIndex = fromIndex + pageSize >= content.size() ? content.size() : fromIndex + pageSize;
return content.subList(fromIndex , toIndex);
}
return new ArrayList<T>();
}
}
PageableUtils.java
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@Getter
@Setter
@NoArgsConstructor
public class PageableUtils{
private Long offset;
private Integer pageNumber;
private Integer pageSize;
private Boolean paged;
private Boolean unpaged;
public PageableUtils(Pageable pageable) {
this.offset = pageable.getOffset();
this.pageNumber = pageable.getPageNumber();
this.pageSize = pageable.getPageSize();
}
}
全部评论