User Entity

컬럼 - PK 아이디, 유저네임, 패스워드, 역할

package com.sample.springjwt.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Entity
@Setter
@Getter
public class UserEntity {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String username;
    private String password;

    private String role;

}

JoinDto

이름과 비밀번호만 입력 받기

package com.sample.springjwt.dto;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class JoinDto {

    private String username;
    private String password;

}

JoinController

“/join” url 을 가지는 회원가입 API

package com.sample.springjwt.controller;

import com.sample.springjwt.dto.JoinDto;
import com.sample.springjwt.service.JoinService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@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 "ok";
    }

}

JoinService

유저레포지토리로 입력받은 이메일이 DB에 있는지 중복 확인하고

→ 이미 존재하면 바로 리턴

→ 존재하지 않을 때 회원가입 진행

UserEntity에 이메일과 인코딩한 비밀번호와 역할을 넣고 save() 메서드로 저장

package com.sample.springjwt.service;

import com.sample.springjwt.dto.JoinDto;
import com.sample.springjwt.entity.UserEntity;
import com.sample.springjwt.repository.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@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));
        data.setRole("ROLE_ADMIN");

        userRepository.save(data);

    }
}

BCryptPasswordEncoder