Spring boot

입금 기능

yoooon1212 2024. 8. 8. 16:48
작업 순서

1. account/deposit.jsp 파일 생성
2. DepositDTO 파일 생성
3. 입금 기능 만들어 보기
4. 전체 코드 확인 하기
5. 오류 테스트 확인 하기

 

 

dto 패키지에 DepositDTO.java 생성
package com.tenco.bank.dto;

import lombok.Data;

@Data
public class DepositDTO {
	
	private Long amount; 
	private String dAccountNumber; 
}

 

 

account 폴더에 deposit.jsp 생성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- 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>
	<form action="/account/deposit" method="post">
        <div class="form-group">
            <label for="amount">입금 금액:</label> <input type="number" class="form-control" placeholder="Enter amount" id="amount" name="amount" value="1000">
        </div>
        <div class="form-group">
            <label for="dAccountNumber">입금 계좌 번호:</label> <input type="text" class="form-control" placeholder="Enter account number" id="dAccountNumber" name="dAccountNumber" value="1111">
        </div>
        <div class="text-right">
            <button type="submit" class="btn btn-primary">입금</button>
        </div>
    </form>
</div>
<!-- end of col-sm-8  -->
</div>
</div>
<!-- end of content.jsp(xxx.jsp)   -->

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

 

 

결과 화면

 

 

 

 

	// 입금 기능 만들기
	@Transactional
	public void updateAccountDeposit(DepositDTO dto, Integer principalId) {
		
		// 1. 계좌 존재 여부를 확인
		Account accountEntity = accountRepository.findByNumber(dto.getDAccountNumber());
		if(accountEntity == null) {
			throw new DataDeliveryException(Define.NOT_EXIST_ACCOUNT, HttpStatus.BAD_REQUEST);
		}
		
		// 2. 본인 계좌 여부 확인
		accountEntity.checkOwner(principalId);
		
		// 3. 입금 처리
		accountEntity.deposit(dto.getAmount());
		accountRepository.updateById(accountEntity);
		
		// 4. history 테이블에 거래 내역 등록
		/*
		insert into history_tb(amount, w_balance, d_balance, w_account_id, d_account_id)
		                values(#{amount}, #{wBalance}, #{dBalance}, #{wAccountId}, #{dAccountId} )	
		*/
		
		History history = new History();
		history.setAmount(dto.getAmount());
		history.setWBalance(null);
		history.setDBalance(accountEntity.getBalance());
		history.setWAccountId(null);
		history.setDAccountId(accountEntity.getId());
		
		int rowResultCount = historyRepository.insert(history);
		if(rowResultCount != 1) {
			throw new DataDeliveryException(Define.FAILED_PROCESSING, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

 

입금 처리 흐름

 

1. 계좌 존재 여부를 확인
2. 본인 계좌 여부 확인
3. 입금 처리
4. history 테이블에 거래 내역 등록
5. 트랜잭션 처리

 

account.xml
	<update id="updateById">
		update account_tb set number = #{number}, password = #{password},
			balance = #{balance}, user_id = #{userId} where id = #{id}
	</update>

이 코드는 3번 입금 처리에 사용된 메서드의 Update 쿼리문입니다. 

 

AccountController
	// 입금 페이지 요청
	@GetMapping("/deposit")
	public String depositPage() {
		User principal = (User) session.getAttribute(Define.PRINCIPAL);
		if (principal == null) {
			throw new UnAuthorizedException(Define.NOT_AN_AUTHENTICATED_USER, HttpStatus.UNAUTHORIZED);
		}
		return "account/deposit";
	}

	// 입금 처리 기능 만들기
	@PostMapping("/deposit")
	public String depositProc(DepositDTO dto) {
		User principal = (User) session.getAttribute(Define.PRINCIPAL);
		if (principal == null) {
			throw new UnAuthorizedException(Define.NOT_AN_AUTHENTICATED_USER, HttpStatus.UNAUTHORIZED);
		}

		// 유효성 검사(자바 코드를 개발) --> 스프링부트 @Valid 라이브러리가 존재
		if (dto.getAmount() == null) {
			throw new DataDeliveryException(Define.ENTER_YOUR_BALANCE, HttpStatus.BAD_REQUEST);
		}

		if (dto.getAmount().longValue() <= 0) {
			throw new DataDeliveryException(Define.D_BALANCE_VALUE, HttpStatus.BAD_REQUEST);
		}

		if (dto.getDAccountNumber() == null) {
			throw new DataDeliveryException(Define.ENTER_YOUR_ACCOUNT_NUMBER, HttpStatus.BAD_REQUEST);
		}

		accountService.updateAccountDeposit(dto, principal.getId());

		return "redirect:/account/list";
	}

 

 

결과 확인 

 

 

입금하기 링크를 누르면

 

 

deposit.jsp 화면이 뜹니다. 

 

이때 입금 금액, 입금할 계좌 번호를 입력하여

입금 버튼을 누르면 

 

 

 

잔액이 2300 이 되는 것을 확인할 수 있습니다.

 

 

 

 

 

DB를 보시면

 

 

AMOUNT(거래금액) 1000

W_ACCOUNT_ID(출금 계좌 ID) null

D_ACCOUNT_ID(입금 계좌 ID) 1

W_BALANCE(출금 계좌 잔액) null

D_BALANCE(입금 계좌 잔액) 2300

 

 

값이 들어온 것을 확인할 수 있습니다. 

 


코드를 해석하자면

D_ACCOUNT_ID(입금 계좌 ID)가 1인 길동이

 

자신의 계좌에 

AMOUNT(거래금액) 1000를 입금해서 

 

D_BALANCE(입금 계좌 잔액)이 2300이 되었습니다.

 

 

이는 우리가 저축을 위해 은행에 돈을 넣을 때 일어나는 일과 같습니다. 

 

 

 


입금 이전 계좌 상황

 

 

입금 이후 계좌 상황