Springboot

[SpringBoot] 11. 회원가입 - 트랜잭션, 예외 처리,H2 테이블

Song hyun 2024. 8. 6. 16:37
728x90
반응형

 

1. 사전 기반 지식 : DTO 클래스와 Model 클래스

(1) 코드의 가독성 및 유지 보수성

(2) 객체

 

2. 
(1) userController

package com.tenco.bank.controller;

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

import com.tenco.bank.handler.Exception.DataDeliveryException;
import com.tenco.bank.repository.interfaces.UserRepository;
import com.tenco.bank.repository.model.SignUpDTO;
import com.tenco.bank.service.UserService;

@Controller // IoC의 대상(싱글톤 패턴으로 관리된다.) 
@RequestMapping("/user") // 대문 처리
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 회원 가입 페이지 요청
	 * 주소 설계 : http://localhost:8080/user/sign-up
	 * @return signUp.jsp
	 */
	@GetMapping("/sign-up")
	public String signUpPage() {
		// prefix: /WEB-INF/view
		// suffix: .jsp
		// return: user/signUp
		return "user/signUp";
	}
	
	/**
	 * 회원 가입 로직 처리 요청
	 * 주소 설계 : http://localhost:8080/user/sign-up
	 * @param dto
	 * @return
	 */
	@PostMapping("/sign-up")
	public String signUpProc(SignUpDTO dto) {
		// controller에서 일반적인 코드 작업
		// 1. 인증 검사 (여기서는 인증검사 불필요!)
		// 2. 유효성 검사
		if(dto.getUsername()==null || dto.getUsername().isEmpty()) {
			throw new DataDeliveryException("username을 입력하세요", HttpStatus.BAD_REQUEST);
		}
		
		if(dto.getPassword()==null || dto.getPassword().isEmpty()) {
			throw new DataDeliveryException("password을 입력하세요", HttpStatus.BAD_REQUEST);
		}
		
		if(dto.getFullname()==null || dto.getFullname().isEmpty()) {
			throw new DataDeliveryException("fullname을 입력하세요", HttpStatus.BAD_REQUEST);
		}
		
		// 서비스 객체로 전달
		userService.createUser(dto);
		
		// 추후 수정 예정
		return "redirect:/index/";
	}
}

 

(2) userService

package com.tenco.bank.service;

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

import com.tenco.bank.handler.Exception.DataDeliveryException;
import com.tenco.bank.handler.Exception.RedirectException;
import com.tenco.bank.repository.interfaces.UserRepository;
import com.tenco.bank.repository.model.SignUpDTO;
import com.tenco.bank.repository.model.User;

@Service // 제어의 역전(IoC)의 대상이 된다. (싱글톤으로 관리되는 객체)
public class UserService {
	
	// DI = 의존 주입 (Dependency Injection)
	@Autowired // 자동으로 객체를 반환해, 메모리에 올린다.
	private UserRepository userRepository;
	
	// @Autowired 어노테이션으로 대체 가능!
	// 생성자 의존 주입 - DI (IoC와 DI는 묶음이다.)
//  public UserService(UserRepository userRepository) {
//		this.userRepository=userRepository;
//  }
	
	
	/**
	 * 
	 * 회원 등록 서비스 기능
	 * 트랜잭션 처리 필수!
	 * @param dto
	 */
	@Transactional // 트랜잭션 처리는 반드시 습관화
	public void createUser(SignUpDTO dto) {
		int result = 0;
		
		try {
			result = userRepository.insert(dto.toUser());
		} catch (DataAccessException e) {
			throw new DataDeliveryException("잘못된 처리입니다.", HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (Exception e) {
			throw new RedirectException("알 수 없는 오류입니다.", HttpStatus.SERVICE_UNAVAILABLE);
		}	
		
		if(result!=1) {
			throw new DataDeliveryException("회원가입 실패", HttpStatus.INTERNAL_SERVER_ERROR);
		}
		
	}
}

 

728x90
반응형