Spring Security + JWT 3

johaS2·2025년 2월 4일

회원가입 로직 구현

@Setter
@Getter
public class JoinDTO {
    private String username;
    private String password;
}

DTO?

계층 간 데이터 전달을 위한 객체
데이터베이스와 직접적인 관계가 없다, 서버와 클라이언트 간 데이터 교환을 위해 사용
주로 요청 및 응답에 사용!

DTO랑 Entity를 함께 사용하는 이유 ?

  1. 클라이언트와 서버 간 데이터 분리
  2. 엔티티 보호
  3. 유효성 검사 빛 변환
  4. 계층 간 데이터 이동 - 서비스, 컨트롤러, 클라이언트 간 DTO를 사용해서, 엔티티 노출되지 않게 함

JoinController

@Controller
@ResponseBody
public class JoinController {

    private final JoinService joinService; // 주입

    public JoinController(JoinService joinService) { // 생성자 주입방식 사용 권장!
        this.joinService = joinService;
    }

    @PostMapping("/join")
    public String joinProcess(JoinDTO joinDTO) {

        joinService.joinProcess(joinDTO);

        return "success";
    }
}

JoinService

@Service
public class JoinService {

    private final UserRepository userRepository;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public JoinService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    public void joinProcess(JoinDTO joinDTO) {
        String username = joinDTO.getUsername();
        String password = joinDTO.getPassword();

        Boolean isExist = userRepository.existsByUsername(username);

        if (isExist) {
            return;
        }

        UserEntity data = new UserEntity();

        data.setUsername(username);
        data.setPassword(bCryptPasswordEncoder.encode(password)); // encode해서 넣어야함
        data.setRole("ROLE_ADMIN");

        userRepository.save(data);
    }
}

Service?

  • Service계층은 Controller와 Repository 사이에서 중간 역할을 하며, 실제 서비스의 핵심적인 처리를 담당!
  • 회원가입, 로그인, 게시물 관리 등과 같은 핵심 기능들이 서비스에서 처리
  • 유지보수 확장성 - Controller는 요청을 받고 응답하는 역할만 해서 코드가 간결해짐
  • 재사용성

UserRepository

public interface UserRepository extends JpaRepository<UserEntity, Integer> {
}

UserRepository 만드는 이유

  • 데이터베이스에서 UserEntity 테이블을 쉽게 다룰 수 있도록 도와주는 역할
  • Spring Data JPA를 사용하면, SQL을 직접 작성하지 않아도 자동으로 데이터베이스 작업을 처리할수 있음
  • JpaRepository를 통해 자동으로 CRUD 메서드를 제공해줌
  • save(UserEntity user), findById(Integer id), findAll(), delete(UserEntity user) 이런 메서드들!
profile
passionate !!

0개의 댓글