💡 학습목표
1. 계좌 생성 form 확인
2. 계좌 생성 페이지 요청 시 인증 로직 구현
URL 추가 (/account/save)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/layout/header.jsp"%>
<div class="col-sm-8">
<h2>계좌 생성 페이지(인증)</h2>
<h5>어서오세요 환영합니다.</h5>
<div class="bg-light p-md-5 h-75">
<div class="form-group">
<form action="/account/save" method="post">
<div class="form-group">
<label for="number">계좌번호</label>
<input type="text" class="form-control" id="number" placeholder="생성 계좌번호를 입력하세요" name="number">
</div>
<div class="form-group">
<label for="password">계좌 비밀번호</label>
<input type="password" class="form-control" id="password" placeholder="계좌 비밀번호를 입력하세요" name="password">
</div>
<div class="form-group">
<label for="balance">입금 금액</label>
<input type="text" class="form-control" id="balance" placeholder="입금 금액을 입력하세요" name="balance">
</div>
<button type="submit" class="btn btn-primary">계좌 생성</button>
</form>
</div>
</div>
</div>
</div>
</div>
<%@ include file="/WEB-INF/view/layout/footer.jsp"%>
/**
* 계좌 생성 페이지 이동
*/
@GetMapping("/save")
public String save() {
// 1. 인증 여부 확인
User user = (User)session.getAttribute("principal");
if(user == null) {
throw new UnAuthorizedException("로그인을 먼저 해주세요.", HttpStatus.UNAUTHORIZED);
}
return "account/save";
}
exception Handler 처리
// 로그인을 하지 않았을 경우 예외 처리
@ExceptionHandler(UnAuthorizedException.class)
public String notLoginException(UnAuthorizedException e) {
StringBuffer sb = new StringBuffer();
sb.append("<script>");
sb.append("alert( ' " + e.getMessage() +" ' );"); // 문자열 안에 반드시 ; 콜론 붙이기
sb.append("history.back();");
sb.append("</script>");
return sb.toString();
}
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);
}
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";
}
}
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);
}
}
}
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); // 계좌번호로 계좌 존재 여부 확인
}
<insert id="insert">
insert into account_tb (number, password, balance, user_id, created_at)
values(#{number}, #{password}, #{balance}, #{userId}, now())
</insert>
package com.tencoding.bank.util;
// 스프링 서버를 만들 때 서블릿 객체 - 상태값을 공유하는 변수 사용 지양
public class Define {
public final static String PRINCIPAL = "principal";
}