Springboot

[Springboot] 29. 계좌 상세 보기 기능(5단계-계좌 목록 페이징 처리)

Song hyun 2024. 8. 12. 19:52
728x90
반응형

[Springboot] 29. 계좌 상세 보기 기능(5단계-계좌 목록 페이징 처리)

 

 

 

1. list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!-- header.jsp  -->
<%@ include file="/WEB-INF/view/layout/header.jsp"%>

<!-- start of content.jsp(xxx.jsp)   -->
<div class="col-sm-8">
	<h2>계좌 목록(인증)</h2>
	<h5>Bank App에 오신걸 환영합니다</h5>
	
	<c:choose>
		<c:when test="${accountList!=null}">
			<%-- 계좌 존재 : html 주석 -- 오류 --%>
			<table class="table">
				<thead>
					<tr>
						<th>계좌 번호</th>
						<th>잔액</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="account" items="${accountList}">
						<tr>
							<%-- --%>
							<td><a href="/account/detail/${account.id}?type=all&currentPageNum=1">${account.number}</a></td>
							<td><a><fmt:formatNumber value="${account.balance}" type="currency"/> </a></td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</c:when>
		
		<c:otherwise>
			<div class="jumbotron display-4">
				<h5>아직 생성된 계좌가 없습니다.</h5>
			</div>
		</c:otherwise>
	</c:choose>
	<%-- 계좌가 없는 경우와 있는 경우를 분리하자. --%>
	<%-- 계좌가 있는 사용자일 경우, 반복문을 활용할 예정 --%>
	
	<div class="d-flex justify-content-center">
		<ul class="pagination">
			<li class="page-item <c:if test="${currentPage==1}">disabled</c:if>">
			<a class="page-link" href="?currentPage=${currentPage-1}">previous</a></li>&nbsp;
			
			<c:forEach begin="1" end="${totalPages}" var="page">
				<li class="page-item <c:if test='${page==currentPage}'> active</c:if>">
				<a class="page-link">${page}</a></li>&nbsp;
			</c:forEach>
			
			<li class="page-item <c:if test='${currentPage==totalPages}'>disabled</c:if>">
			<a class="page-link" href="?currentPage=${currentPage+1}">next</a></li>&nbsp;
		</ul>
	</div>
	
</div>
<%-- end of col-sm-8  --%>
</div>
</div>

<%-- footer.jsp  --%>
<%@ include file="/WEB-INF/view/layout/footer.jsp"%>

 

 

2. AccountController.java

	/**
	 * 계좌 목록 화면 요청
	 * 주소 설계: http://localhost:8080/account/list ...
	 * @return list.jsp
	 */
	@GetMapping({"/list","/"})
	public String listPage(Model model,
			@RequestParam(name="currentPage", defaultValue="1") Integer currentPage, 
			@RequestParam(name="totalPage", defaultValue="3") Integer totalPage) {
		
		// 1. 인증 검사
		User principal=(User)session.getAttribute("principal");
		if(principal==null) {
			throw new UnAuthorizedException(Define.NOT_AN_AUTHENTICATED_USER, HttpStatus.UNAUTHORIZED);
		}
		
		// 2. 유효성 검사
		// 3. 서비스 호출
		
		
		if(currentPage==null) {
			currentPage=1;
		}
		Integer limit=2; // 한 페이지당 내역 수
		Integer offset=currentPage; // 몇번부터 뽑을지
		// 총 내역 수
		Integer totalAccount=(accountService.readAccountListByUserId(principal.getId())).size();
		// 총 페이지 수
		Integer totalPages=(int)Math.ceil((double)totalAccount/limit);
		
		// 페이지별 내역 수
		List<Account> accountList=accountService.readAccountListByUserIdForPaging(principal.getId(),limit,currentPage);
		if(accountList.isEmpty()) {
			model.addAttribute("accountList",null);
		} else {
			model.addAttribute("accountList",accountList);
		}
		
		
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("totalPages", totalPages);
		model.addAttribute("totalPages", totalPages);
		// JSP 데이터를 넣어주는 방법
		return "account/list";
	}

 

 

3. AccountService.java

	// 원자성을 위한 트랜잭션 처리
	@Transactional
	public List<Account> readAccountListByUserIdForPaging(Integer userId, Integer limit, Integer offset) {
		List<Account> accountListEntity=new ArrayList<>();
		
		try {
			System.out.println(userId);
			System.out.println(limit);
			System.out.println(offset);
			accountListEntity=accountRepository.readAccountListByUserIdForPaging(userId,limit,offset);
		} catch (DataAccessException e) {
			throw new DataDeliveryException(Define.INVALID_INPUT, HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (Exception e) {
			throw new RedirectException(Define.UNKNOWN, HttpStatus.SERVICE_UNAVAILABLE);
		}
		return accountListEntity;
		
	}

 

 

4. AccountRepository.interface / Account.xml

	public List<Account> readAccountListByUserIdForPaging(@Param("userId") Integer principalId, 
																@Param("limit")Integer limit, 
																@Param("offset")Integer offset);
<select id="readAccountListByUserIdForPaging"  resultType="com.tenco.bank.repository.model.Account">
		select * from account_tb where user_id = #{userId} 
		limit #{limit} offset #{offset}
	</select>
728x90
반응형