ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • bank app 17 - 계좌 상세보기(2)
    spring boot 2023. 4. 20. 12:50

     

     

     

     

     

    a 태그를 추가 해준다.

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ include file="/WEB-INF/view/layout/header.jsp"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <!-- todo main 영역으로 지정 예정  -->
    <div class="col-sm-8">
    	<h2>나의 계좌 목록</h2>
    	<h5>어서오세요 환영합니다</h5>
    	<div class="bg-light p-md-5 h-75">
    	<c:choose>
    		<c:when test="${accountList != null}">
    			<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}">${account.number}</a></td>
    			<td>${account.balance}</td>
    			</tr>
    		</c:forEach>
    		</tbody>
    		</table>
    		</c:when>
    		<c:otherwise>
    			<p>아직 생성된 계좌가 없습니다</p>
    		</c:otherwise>
    	</c:choose>
    	</div>
    	<br>
    
    </div>
    
    <%@ include file="/WEB-INF/view/layout/footer.jsp"%>

     

     

     

     

     

    로그인 유효성 검사 만들어주고 리턴을 detail.jsp로 지정해주자.

    @GetMapping("/detail/{accountId}")

    public String detail(@PathVariable Integer accountId) {

     

    if (session.getAttribute(Define.PRINCIPAL) == null) {

    throw new UnAuthorizedException("로그인 먼저 해주세요", HttpStatus.UNAUTHORIZED);

    }

    System.out.println("accountId : " + accountId);

    return "/account/detail";

    }

     

    a태그 링크를 타고 들어갔을때 accountId가 잘 찍히는지 확인해보자

     

     

     

     

     

     

    세션 값을 a태그를 타고 들어갔을 때 model 객체를 이용하여 값을 들고온다.

    @GetMapping("/detail/{accountId}")
    	public String detail(@PathVariable Integer accountId, Model model) {
    		
    		User principal = (User)session.getAttribute(Define.PRINCIPAL);
    				
    		if (session.getAttribute(Define.PRINCIPAL) == null) {
    			throw new UnAuthorizedException("로그인 먼저 해주세요", HttpStatus.UNAUTHORIZED);
    		}
    		
    		// 화면을 구성하기 위해 필요한 데이터
    		
    		// 소유자 이름
    		// 계좌번호(1개), 계좌 잔액
    		// 거래 내역
    		model.addAttribute("principal",principal);
    		
    		// todo accountId 로 select 처리
    		//Account account = accountService.readAccountList(accountId)
    		
    		System.out.println("accountId : " + accountId);
    		return "/account/detail";
    	}

     

    detail.jsp에 로그인 한 사람의 이름이 뜨도록 jstl을 사용해서 이름이 뜨게 수정한다.

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ include file="/WEB-INF/view/layout/header.jsp"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <style>
    .user--box{
    	border: 1px solid black;
    	padding: 10px;
    	
    }
    
    </style>
    <!-- todo main 영역으로 지정 예정  -->
    <div class="col-sm-8 d-flex flex-column">
    	<h2>계좌 상세 보기(인증)</h2>
    	<h5>어서오세요 환영합니다</h5>
    	<div class="bg-light p-md-5 h-75">
    		
    		<div class="user--box">
    			${principal.username}님 계좌<br>
    			계좌번호 : 9999<br>
    			잔액 : 9999원
    		</div>
    		<br>
    		<div>
    		<a href="#">전체</a>&nbsp;
    		<a href="#">입금</a>&nbsp;
    		<a href="#">출금</a>
    		</div>
    		<br>
    		<table class="table">
    		<thead>
    		<tr>
    			<th>날짜</th>
    			<th>보낸이</th>
    			<th>받은이</th>
    			<th>입출금금액</th>
    			<th>계좌잔액</th>
    		</tr>
    		</thead>
    		<tbody>
    		<tr>
    			<th>2023.04.20	10.10.11</th>
    			<th>ATM</th>
    			<th>1111 계좌</th>
    			<th>999원</th>
    			<th>3999원</th>
    		</tr>
    		</tbody>
    		</table>
    				
    	</div>
    	<br>
    
    </div>
    
    <%@ include file="/WEB-INF/view/layout/footer.jsp"%>

     

     

     

     

     

     


    계좌번호로 계좌정보 찾는 기능 레파지토리에 찾아주기

    package com.tenco.bank.repository.interfaces;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Mapper;
    
    import com.tenco.bank.repository.model.Account;
    
    @Mapper	//mybatis 연결
    public interface AccountRepository {
    	
    	public int insert(Account account);
    	
    	public int updateById(Account account);
    	
    	public int deleteById(int id);
    	
    	public List<Account> findAll();	// 고민
    	// 한사람의 2개이상의 계좌정보 (관리자가 쓸 기능 만들 예정)
    	public Account findById(int id);
    	
    	public List<Account> findByUserId(Integer userId);
    	
    	//코드 추가 - 계좌 번호로 찾는 기능 추가
    	public Account findByNumber(String number);
    }

     

     

    서비스에 readAccount 만들고 레파지토리 기능,유효성검사 해주고

    Integer userid로 되어있는걸 id로 리팩토링 하기

    // 단일 계좌 검색 기능
    	public Account readAccount(Integer id) {
    		Account accountEntity = accountRepository.findById(id);
    		if (accountEntity == null) {
    			throw new CustomRestfullException("해당 계좌를 찾을 수 없습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
    		}
    		return accountEntity;
    	}

     

    컨트롤러에 들고와서 detail.jsp에 값을 들고오기

    // 계좌 상세 보기 페이지
    	@GetMapping("/detail/{id}")
    	public String detail(@PathVariable Integer id, Model model) {
    		
    		User principal = (User)session.getAttribute(Define.PRINCIPAL);
    				
    		if (session.getAttribute(Define.PRINCIPAL) == null) {
    			throw new UnAuthorizedException("로그인 먼저 해주세요", HttpStatus.UNAUTHORIZED);
    		}
    		
    		Account account = accountService.readAccount(id);
    		// 화면을 구성하기 위해 필요한 데이터
    		// 소유자 이름
    		// 계좌번호(1개), 계좌 잔액
    		// 거래 내역
    		model.addAttribute("principal",principal);
    		model.addAttribute("account",account);
    		
    		return "/account/detail";
    	}
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ include file="/WEB-INF/view/layout/header.jsp"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <style>
    .user--box{
    	border: 1px solid black;
    	padding: 10px;
    	
    }
    
    </style>
    <!-- todo main 영역으로 지정 예정  -->
    <div class="col-sm-8 d-flex flex-column">
    	<h2>계좌 상세 보기(인증)</h2>
    	<h5>어서오세요 환영합니다</h5>
    	<div class="bg-light p-md-5 h-75">
    		
    		<div class="user--box">
    			${principal.username}님 계좌<br>
    			계좌번호 : ${account.number}<br>
    			잔액 : ${account.balance}원
    		</div>
    		<br>
    		<div>
    		<a href="#">전체</a>&nbsp;
    		<a href="#">입금</a>&nbsp;
    		<a href="#">출금</a>
    		</div>
    		<br>
    		<table class="table">
    		<thead>
    		<tr>
    			<th>날짜</th>
    			<th>보낸이</th>
    			<th>받은이</th>
    			<th>입출금금액</th>
    			<th>계좌잔액</th>
    		</tr>
    		</thead>
    		<tbody>
    		<tr>
    			<th>2023.04.20	10.10.11</th>
    			<th>ATM</th>
    			<th>1111 계좌</th>
    			<th>999원</th>
    			<th>3999원</th>
    		</tr>
    		</tbody>
    		</table>
    				
    	</div>
    	<br>
    
    </div>
    
    <%@ include file="/WEB-INF/view/layout/footer.jsp"%>

     

     

     

     

     

     

     

     

     

    findById에서 by로 써서 에러가 났다. (대 . 소문자를 조심해주자! )

     

     

    dto안에 response 패키지를 만들어준다

     

     

    마이 페이지에 뽑을 dto를 설계 해준다.

    package com.tenco.bank.dto.response;
    
    import java.sql.Timestamp;
    
    import lombok.Data;
    
    @Data
    public class HistoryDto {
    	private Integer id;
    	private Long amount;
    	private Long balance;
    	private String sender;
    	private String receiver;
    	private Timestamp createdAt;
    }

     

    HistoryRepository

    (매개변수를 @Param으로 명시 해주어야 인식이 된다)

     

    package com.tenco.bank.repository.interfaces;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    
    import com.tenco.bank.dto.response.HistoryDto;
    import com.tenco.bank.repository.model.History;
    
    @Mapper // 반드시 지정하기 !
    public interface HistoryRepository {
    	
    	public int insert(History history);
    	public int updateById(History history);
    	public int deleteById(int id);
    	public History findById(int id);
    	public List<History> findAll();
    	// 매개변수 갯수가 2개 이상이면 반드시 파라미터 이름을 명시 해주자.
    	public List<HistoryDto> findByIdHistoryType(@Param("type") String type,@Param("id") Integer id);
    }

     

     

     

     

     

    history.xml에 쿼리문 설계 해보기

    <select id="findByIdHistoryType" resultType="com.tenco.bank.dto.response.HistoryDto">
    		<if test="type == 'deposit'">
    			select h.id, h.amount, h.d_balance as balance, h.created_at,
    			ifnull(wa.number, 'ATM') as sender, 
    	    	da.number as receiver 
    			from history_tb as h 
    			left join account_tb as da 
    			on h.d_account_id = da.id 
    			left join account_tb as wa 
    			on h.w_account_id = wa.id 
    			where h.d_account_id = #{id};
    		</if>
    		<if test="type == 'withdraw'">
    			select h.id, h.amount, h.w_balance as balance, h.created_at,
    		    ifnull(da.number, 'AMT') as recevier, 
    	        wa.number as sender 
    			from history_tb as h 
    			left join account_tb as wa
    			on h.w_account_id = wa.id 
    			left join account_tb as da 
    			on h.d_account_id = da.id 
    			where h.w_account_id = #{id};
    		</if>
    		<if test="type == 'all'">
    			select h.id, h.amount,
    			case when h.w_account_id = #{id} then (h.w_balance)
    	     	when h.d_account_id = #{id} then (h.d_balance) 
    		    end as balance, 
    		    ifnull(wa.number, 'ATM') as sender, 
    		    ifnull(da.number, 'ATM') as receiver, 
    		    h.created_at
    			from history_tb as h 
    			left join account_tb as da 
    			on h.d_account_id = da.id 
    			left join account_tb as wa 
    			on h.w_account_id = wa.id 
    			where h.d_account_id = #{id} or h.w_account_id = #{id};
    		</if>
    	
    	</select>

     

    AccountController

    // 계좌 상세 보기 페이지
    	@GetMapping("/detail/{id}")
    	public String detail(@PathVariable Integer id,@RequestParam(name = "type", defaultValue = "all", required = false) String type, Model model) {
    		
    		User principal = (User)session.getAttribute(Define.PRINCIPAL);
    				
    		if (session.getAttribute(Define.PRINCIPAL) == null) {
    			throw new UnAuthorizedException("로그인 먼저 해주세요", HttpStatus.UNAUTHORIZED);
    		}
    		System.out.println("type : " + type);
    		Account account = accountService.readAccount(id);
    		List<HistoryDto> historyList = accountService.readHistoryListByAccount(type, id);
    		System.out.println(historyList);
    		// 화면을 구성하기 위해 필요한 데이터
    		// 소유자 이름
    		// 계좌번호(1개), 계좌 잔액
    		// 거래 내역
    		model.addAttribute("principal",principal);
    		model.addAttribute("account",account);
    		model.addAttribute("historyList",historyList);
    		
    		return "/account/detail";
    	}

     

     

     

     

     

    날짜와 계좌잔액을 보면 날짜가 초 말고도 세밀하게 찍히는걸 볼수 있으며

    계좌잔액이 천의 단위로 나뉘어서 표시가 안되어서 가독성이 안좋게 보인다.

    이것을 해결 하기 위해 model에 기능을 만들어 준것처럼 기능을 만들어 주자.

     

     

     

    package com.tenco.bank.dto.response;
    
    import java.sql.Timestamp;
    import java.text.DecimalFormat;
    
    import com.tenco.bank.utils.TimestampUtil;
    
    import lombok.Data;
    
    @Data
    public class HistoryDto {
    	private Integer id;
    	private Long amount;
    	private Long balance;
    	private String sender;
    	private String receiver;
    	private Timestamp createdAt;
    	
    	
    	public String formatCreatedAt() {
    		return TimestampUtil.timestampToString(createdAt);
    	}
    	
    	public String formatBalance() {
    		DecimalFormat df = new DecimalFormat("#,###");
    		String formatNumber = df.format(balance);
    		return formatNumber + "원";
    	}
    }

     

     

    'spring boot' 카테고리의 다른 글

    bank app 19 - (마이그레이션)  (0) 2023.04.21
    bank app 18 - (intercepter 활용)  (0) 2023.04.21
    bank app 16 - 계좌 상세보기(1)  (0) 2023.04.20
    bank app 10  (0) 2023.04.18
    bank app 9 - 회원가입(트랜잭션처리)  (0) 2023.04.18
Designed by Tistory.