Programming/JAVA
[JAVA] 페이징 처리
100winone
2019. 11. 25. 12:26
오늘은 페이징 처리를 해보겠다.
거창하게 홈페이지에 당장 적용하는 것은 아니고, 페이지를 분리시켜서 표출할 수 있도록 하는 자바코드를 한번 살펴보자.
// PaginationInfo.java
public class PaginationInfo {
private int totalPage;
private int firstIndex = 0;
private int lastIndex = 0;
private int cntPerPage;
public PaginationInfo(int totalCnt, int pageIndex, int cntPerPage) {
super();
this.cntPerPage = cntPerPage;
this.totalPage = totalCnt / cntPerPage;
if (totalPage != 0) {
if(this.totalPage % this.cntPerPage > 0) {
this.totalPage++;
}
if(this.totalPage < pageIndex) {
pageIndex = this.totalPage;
}
this.firstIndex = ((pageIndex - 1) * cntPerPage +1);
this.lastIndex = this.firstIndex + cntPerPage - 1;
}
else
{
this.totalPage = 1;
pageIndex = this.totalPage;
firstIndex = 1;
lastIndex = totalCnt;
}
}
public int getFirstIndex() {
return this.firstIndex;
}
public int getLastIndex() {
return this.lastIndex;
}
}
일단 기본적인 코드는 이렇게 된다.
totalPage가 0이라는 뜻은 매개변수로 받는 cntPerPage(한 페이지당 표시되는 갯수)가 totalCnt(총 아이템의 갯수) 보다 크다는 뜻이다. 따라서 totalPage가 0인 경우는 else 문에 따로 정의를 해주었다.
이 것을 스프링 부트에 적용한다면?
// RestController.java
if(totalCnt > 0) {
PaginationInfo page = new PaginationInfo(totalCnt, params.getPageIndex(), params.getCntPerPage());
params.setFirstIndex(page.getFirstIndex());
params.setLastIndex(page.getLastIndex());
try {
list = restService.getVehicleCount(params);
LOGGER.info("차량 종류, 종류별 사고 발생 건수 조회 성공");
res.getResponse().getBody().getItems().setItem(list);
res.getResponse().getBody().setItems(res.getResponse().getBody().getItems());
res.getResponse().getHeader().setResultCode(CommonVariable.SUCCESS_CODE);
res.getResponse().getHeader().setResultMsg(CommonVariable.SUCCESS_MSG);
res.getResponse().setBody(res.getResponse().getBody());
} catch (Exception e) {
LOGGER.error("차량 종류, 종류별 사고 발생 건수 조회 실패", e);
}
Parameter만 잘 주고받는다면 정상적으로 실행될 것이다.