• 티스토리 홈
  • 프로필사진
    Song hyun
  • 방명록
  • 공지사항
  • 태그
  • 블로그 관리
  • 글 작성
Song hyun
  • 프로필사진
    Song hyun
    • 분류 전체보기 (780)
      • 백준 (0)
      • 영어 (2)
        • Diary (0)
        • Toast Masters (2)
      • 메모 (13)
      • 설치 메뉴얼 (30)
      • Java (178)
      • MySQL (60)
      • JSP (67)
      • Springboot (46)
      • HTML,CSS, JS (71)
        • HTML (8)
        • CSS (12)
        • JavaScript (37)
        • HTML&CSS 스터디 (13)
      • C++ (7)
      • Linux (7)
      • JPA (34)
      • Kotlin (2)
      • Flutter (42)
      • Error Note (39)
      • 디자인 패턴 (12)
      • 디지털논리회로 (4)
      • 데이터베이스 시스템 (8)
      • 알고리즘 (7)
      • 운영체제 (3)
      • 이산수학 (3)
      • 인공지능 (1)
      • 자료 구조 (14)
        • 기본 개념 (14)
        • 자료구조 스터디 (0)
      • 💡My project (76)
        • 팩맨 : Java Swing 게임 제작 프로젝트 (6)
        • 네이트톡 : Java 소켓 통신 프로젝트 (4)
        • 포켓옥션 : HikariCP&JDBC CRUD 프.. (3)
        • 이지 부산 : BDIA-Devton 2024 프로.. (20)
        • 그린 유니버시티 : JSP를 사용한 학사관리 프로.. (1)
        • 애드 포커 : 웹 소켓과 Spring을 사용한 카.. (1)
        • 셸위 : 게임 친구 매칭 사이트 (21)
        • 다모아 : 개발자 중개 플랫폼 (20)
      • 📗스터디 (13)
        • CNN : 웹개발 스터디 (10)
        • Node&React로 유튜브 사이트 만들기 (3)
      • 📙독서 및 강연 기록 (36)
        • 강연 (14)
        • 독서 (22)
  • 방문자 수
    • 전체:
    • 오늘:
    • 어제:
  • 최근 댓글
      등록된 댓글이 없습니다.
    • 최근 공지
        등록된 공지가 없습니다.
      # Home
      # 공지사항
      #
      # 태그
      # 검색결과
      # 방명록
      • [Springboot] 27. 계좌 상세 보기 기능(5단계-JSTL 사용 및 페이징 기능)
        2024년 08월 12일
        • Song hyun
        • 작성자
        • 2024.08.12.:16
        728x90
        반응형

        1. JSTL 태그 사용

        <%@ 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>
        	
        	<div class="bg-light p-md-5">
        		<div class="user--box">
        			${principal.username}님 계좌 <br> 계좌 번호 : ${account.number} <br> 잔액 : <fmt:formatNumber value="${account.balance}" type="currency"/>
        		</div>
        		<br>
        		
        		<div>
        			<a href="/account/detail/${account.id}?type=all&currentPageNum=1" class="btn btn-outline-primary">전체</a>&nbsp;
        			<a href="/account/detail/${account.id}?type=deposit&currentPageNum=1" class="btn btn-outline-primary">입금</a>&nbsp;
        			<a href="/account/detail/${account.id}?type=withdrawal&currentPageNum=1" class="btn btn-outline-primary">출금</a>&nbsp;
        		</div>
        		&nbsp;
        		<table class="table table-striped">
        			<thead>
        				<tr>
        					<th>ID</th>
        					<th>날짜</th>
        					<th>보낸 이</th> <%--sender --%>
        					<th>받은 이</th> <%--receiver --%>
        					<th>입출금 금액</th> <%--amount --%>
        					<th>계좌 잔액</th> <%--balance --%>
        				</tr>
        			</thead>
        			<tbody>
        			<c:forEach var="historyAccount"  items="${historyList}">
        				<tr>
        					<th>${historyAccount.id}</th> 
        					<th><fmt:formatDate value="${historyAccount.createdAt}" pattern="yyyy년 MM월 dd일 hh시 mm분 ss초"/></th> <%--연-월-일 시:분:초 --%>
        					<th>${historyAccount.sender}</th> <%--보낸 이 --%>
        					<th>${historyAccount.receiver}</th> <%--받은 이 --%>
        					<th> <fmt:formatNumber value="${historyAccount.amount}" type="currency"/></th> <%--입출금 금액 --%>
        					<th> <fmt:formatNumber value="${historyAccount.balance}" type="currency"/></th> <%--현재 계좌 잔액 --%>
        				</tr>
        			</c:forEach>
        			</tbody>
        		</table>
        		
        		<div class="pagination">
        		<a href="${accountId}?type=${type}&currentPageNum=${i-1}"><p><</p></a>
        			<c:forEach var="i" begin="1" end="${totalPages}">
        			<c:choose>
        				<c:when test="${i}==${currentPages}">
        					<a class="current-page" href="/detail/${accountId}?type=${type}&currentPageNum=${i}"><b>${i}</b></a>
        				</c:when>
        				<c:otherwise>
        					<a href="${accountId}?type=${type}&currentPageNum=${i}">${i}</a>
        				</c:otherwise>
        			</c:choose>
        			</c:forEach>
        		<a href="${accountId}?type=${type}&currentPageNum=${i+1}"><p>></p></a>
        		</div>
        		
        	</div>
        	
        </div>
        <!-- end of col-sm-8  -->
        </div>
        </div>
        
        <!-- footer.jsp  -->
        <%@ include file="/WEB-INF/view/layout/footer.jsp"%>

         

         

        2. 페이징 기능 추가

        (1) AccountController - 페이징 메서드

        /**
        	 * 계좌 상세 보기 페이지
        	 * 주소 설계 : http://localhost:800/account/detail/${1}?type=all, deposit, withdraw
        	 * @return
        	 */
        	@GetMapping("/detail/{accountId}")
        	public String detail(@PathVariable(name="accountId") Integer accountId,
        			@RequestParam(required=false, name="type") String type, Model model,
        			@RequestParam(name="currentPageNum") Integer currentPageNum) {
        		
        		// 인증 검사
        		User principal=(User)session.getAttribute(Define.PRINCIPAL);
        		if(principal==null) {
        			throw new UnAuthorizedException(Define.NOT_AN_AUTHENTICATED_USER, HttpStatus.UNAUTHORIZED);
        		}
        		
        		
        		// 유효성 검사
        		// arrays.asList() -> array 선언과 동시에 초기화해주는 메서드
        		// 사용자가 선택한 타입(입출금/입금/출금 검색)을 검사한다.
        		List<String> validTypes=Arrays.asList("all","deposit","withdrawal");
        		if(!validTypes.contains(type)) {
        			throw new DataDeliveryException("유효하지 않은 접근입니다.", HttpStatus.BAD_REQUEST);
        		}
        		
        		Integer limit=2;
        	
        		
        		// 계좌/내역 정보
        		Account account = accountService.readAccountById(accountId);
        		Integer totalBoard=(accountService.readHistoryByAccountId(type, accountId)).size(); //총 보드 갯수
        		Integer totalPages=(int)Math.ceil((double)totalBoard/limit);
        		Integer currentPage = currentPageNum;
        		
        		if(currentPage==null) {
        			currentPage=1;
        		}
        		Integer offset;
        		
        		if(currentPage==1) {
        			offset=0;
        		} else {
        			offset=currentPageNum;
        		}
        		
        		System.out.println("accountId"+accountId);
        		
        		List<HistoryAccount> historyList= accountService.readHistoryByAccountIdForPaging(type, accountId,limit,offset);
        		
        		// 페이징 정보 처리
        		
        		
        		model.addAttribute("type", type);
        		model.addAttribute("account",account);
        		model.addAttribute("historyList", historyList);
        		model.addAttribute("totalPages", totalPages);
        		model.addAttribute("currentPage", currentPage);
        		return "account/detail";
        	}

         

         

        (2) AccountService

        /**
        	 * 단일 계좌 거래 내역 조회 (페이지네이션)
        	 * @param type = [all, deposit, withdrawal]
        	 * @param accountId (pk)
        	 * @return 전체, 입금, 출금 거래 내역(3가지 타입 반환)
        	 */
        	@Transactional
        	public List<HistoryAccount> readHistoryByAccountIdForPaging(String type, Integer accountId,Integer limit, Integer offset){
        		List<HistoryAccount> list=new ArrayList<>();
        		list=historyRepository.findByAccountIdAndTypeOfHistoryAndPaging(type, accountId,limit,offset);
        		return list;
        	}
        728x90
        반응형

        'Springboot' 카테고리의 다른 글

        [Springboot] 29. 계좌 상세 보기 기능(5단계-계좌 목록 페이징 처리)  (0) 2024.08.12
        [Springboot] 28. 계좌 상세 보기 기능(5단계-정답 코드)  (1) 2024.08.12
        [Springboot] 26. 계좌 상세 보기 기능(4단계-단위별 포맷)  (0) 2024.08.12
        [Springboot] 25. 계좌 상세 보기 기능(3단계-모델, 레포지토리, 쿼리문 작성)  (0) 2024.08.12
        [Spring] **24. 개념 보충 공부(3)  (0) 2024.08.12
        다음글
        다음 글이 없습니다.
        이전글
        이전 글이 없습니다.
        댓글
      조회된 결과가 없습니다.
      스킨 업데이트 안내
      현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
      ("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)
      목차
      표시할 목차가 없습니다.
        • 안녕하세요
        • 감사해요
        • 잘있어요

        티스토리툴바