BankApp - 계좌 목록 만들기

Gun·2023년 9월 19일

Spring Boot - BankApp

목록 보기
14/25
💡 학습목표
   1. 계좌 목록 쿼리 확인 및 생성
   2. AccountRepository 코드 추가

	<select id="findByUserId" resultType="com.tencoding.bank.repository.model.Account">
		 select * from account_tb where user_id = #{userId}
	</select>

package com.tencoding.bank.repository.interfaces;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.tencoding.bank.repository.model.Account;

@Mapper // 반드시 정의
public interface AccountRepository {
	
	public int insert(Account acount);
	public int updateById(Account acount);
	public int deleteById(Integer id);
	
	public List<Account> findAll();
	public Account findById(Integer id);
	
	public List<Account> findByUserId(Integer principalId);
	public Account findByNumber(String number); // 계좌번호로 계좌 존재 여부 확인
}

package com.tencoding.bank.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tencoding.bank.dto.SaveFormDto;
import com.tencoding.bank.handler.exception.CustomRestfulException;
import com.tencoding.bank.repository.interfaces.AccountRepository;
import com.tencoding.bank.repository.model.Account;

@Service // IoC 대상 + 싱글톤 패턴으로 -> 스프링 컨테이너 메모리에 객체가 생성
public class AccountService {
	
	@Autowired
	private AccountRepository accountRepository;
	
	@Transactional
	public void creatAccount(SaveFormDto saveFormDto, Integer principalId) {
		// 등록 처리 - insert
		Account account = new Account();
		account.setNumber(saveFormDto.getNumber());
		account.setPassword(saveFormDto.getPassword());
		account.setBalance(saveFormDto.getBalance());
		account.setUserId(principalId);
		
		int resultRowCount = accountRepository.insert(account);
		if(resultRowCount != 1) {
			throw new CustomRestfulException("계좌 생성 실패", HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	/**
	 * 계좌 목록 보기 ( 로그인 된 사용자 )
	 * @param userId
	 * @return
	 */
	@Transactional
	public List<Account> readAccountList(Integer userId) {
		List<Account> list = accountRepository.findByUserId(userId);
		return list;
	}
}

package com.tencoding.bank.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tencoding.bank.dto.SaveFormDto;
import com.tencoding.bank.handler.exception.CustomRestfulException;
import com.tencoding.bank.handler.exception.UnAuthorizedException;
import com.tencoding.bank.repository.model.Account;
import com.tencoding.bank.repository.model.User;
import com.tencoding.bank.service.AccountService;
import com.tencoding.bank.util.Define;

@Controller
@RequestMapping("/account")
public class AccountController {
	
	@Autowired
	private HttpSession session;
	@Autowired
	private AccountService accountService;
	
	// 계좌 목록 페이지
	// http://localhost:80/account/list
	
	@GetMapping("/list")
	public String list(Model model) {
		User user = (User)session.getAttribute(Define.PRINCIPAL);;
		if(user == null) {
			throw new UnAuthorizedException("로그인을 먼저 해주세요.", HttpStatus.UNAUTHORIZED);
		}
		
		List<Account> accountList = accountService.readAccountList(user.getId());
		
		if(accountList.isEmpty()) {
			model.addAttribute("accountList", null);
		} else {
			model.addAttribute("accountList", accountList);
		}
		
		return "account/list";
	}
	
	
	// 계좌 생성 페이지
	// http://localhost:80/account/save
	// /account/save - 화면 이동
	/**
	 * 계좌 생성 페이지 이동
	 */
	@GetMapping("/save")
	public String save() {
		// 1. 인증 여부 확인
		
		User user = (User)session.getAttribute(Define.PRINCIPAL);;
		if(user == null) {
			throw new UnAuthorizedException("로그인을 먼저 해주세요.", HttpStatus.UNAUTHORIZED);
		}
		
		return "account/save";
	}
	
	/**
	 * 계좌 생성 로직 구현
	 * @return
	 */
	@PostMapping("/save")
	public String saveProc(SaveFormDto saveFormDto) {
		// 1. 인증 검사
		User user = (User)session.getAttribute(Define.PRINCIPAL);;
		if(user == null) {
			throw new UnAuthorizedException("로그인을 먼저 해주세요.", HttpStatus.UNAUTHORIZED);
		}
		// 2. 유효성 검사
		if(saveFormDto.getNumber() == null
				|| saveFormDto.getNumber().isEmpty()) {
			throw new CustomRestfulException("계좌번호를 입력해주세요.", HttpStatus.BAD_REQUEST);
		}
		
		if(saveFormDto.getPassword() == null
				|| saveFormDto.getPassword().isEmpty()) {
			throw new CustomRestfulException("비밀번호를 입력해주세요.", HttpStatus.BAD_REQUEST);
		}
		
		if(saveFormDto.getBalance() == null 
				|| saveFormDto.getBalance() < 0) {
			throw new CustomRestfulException("잘못된 입력입니다..", HttpStatus.BAD_REQUEST);
		}
		// 3. 서비스 호출
		accountService.creatAccount(saveFormDto, user.getId());
		return "redirect:/account/list";
	}
	
	// 출금 페이지
	// http://localhost:80/account/withdraw
	
	@GetMapping("/withdraw")
	public String withdraw() {
		return "account/withdraw";
	}
	
	// 입금 페이지
	// http://localhost:80/account/deposit
	
	@GetMapping("/deposit")
	public String deposit() {
		return "account/deposit";
	}
	
	// 이체 페이지
	// http://localhost:80/account/transfer
	
	@GetMapping("/transfer")
	public String transfer() {
		return "account/transfer";
	}
	
	
	// TODO - 수정하기
	// 상세 보기 페이지
	// http://localhost:80/account/detail/1
	
	@GetMapping("/detail")
	public String detail() {
		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" %>

<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>
							<td>계좌번호</td>
							<td>잔액</td>
						</tr>
					</thead>
					<tbody>
						<c:forEach var="account" items="${accountList}">
							<tr>
								<td>${account.number}</td>
								<td>${account.balance}</td>
							</tr>
						</c:forEach>
					</tbody>
				</table>
			</c:when>
			<c:otherwise>
				<p>아직 생성된 계좌가 없습니다.</p>
			</c:otherwise>
		</c:choose>
	</div>
	
	
	
	</div>
	</div>
</div>

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

0개의 댓글