[Java] PageModule만들기 (with. Pageable)
2023. 3. 23. 15:49

1. pageModule 클래스 생성 (리스트와 보여지고싶은 페이지블럭수 필요)

package com.laptop.rfid_innotek2.util; 

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.laptop.rfid_innotek2.model.EventHistory;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageModule {
	
	private int nowPage; 
	private int endPage;
	private int startPage;
	private int totalPage;
	
	public void pageSetting(Page<?> list, int displayPage) { 
		this.nowPage = list.getPageable().getPageNumber()+1;
		this.endPage = (int) (Math.ceil(nowPage/(double) displayPage) * displayPage);
		this.startPage = (endPage - displayPage) + 1;
		this.totalPage = list.getTotalPages(); 
		
		if(this.endPage > this.totalPage) {
			this.endPage = this.totalPage;
		}
		
	}

}

 

2. 페이징 처리하고싶은 API에 적용

@GetMapping("/eventHistory/search1") 
public String search1(Model model, @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) { 
	Page<EventHistory> historyList = eventHistoryService.findAll(pageable); 
	
	PageModule pageModule = new PageModule(); 
	int displayPage = 10;   
	
	pageModule.pageSetting(historyList, displayPage); 
	model.addAttribute("pageModule", pageModule);
	model.addAttribute("historyList", historyList);
	return "page/search1";
}

 

3. JSP 페이지에 적용

<div class="pageWrap">
	<div class="numList">
		<c:if test="${!historyList.first}"><div class='leftBtn'><a href="/eventHistory/search1?page=${historyList.number - 1}"> &laquo;</a></div></c:if>  
			<c:forEach var="i" begin="${pageModule.startPage}" end="${pageModule.endPage}">
				<c:choose>
					<c:when test="${i eq pageModule.nowPage}"> 
						<div class="num black"><a style="color:white;" href="/eventHistory/search1?page=${i-1}">${i}</a></div>
					</c:when>
					<c:otherwise>
						<div class="num"><a href="/eventHistory/search1?page=${i-1}">${i}</a></div>
					</c:otherwise>
				</c:choose>
			</c:forEach>
		<c:if test="${!historyList.last}"><div class='rightBtn'><a href="/eventHistory/search1?page=${historyList.number + 1}">&raquo;</a></div></c:if>
	</div>
</div>

 

4. 결과

 


Pageable로 간편하게 사용하려고 만듬.