2. 회원가입
목차
의존성 관계
build.gradle
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' }
|
회원가입을 위한 DTO 만들기
SignUpRequest.java
@Data @AllArgsConstructor @NoArgsConstructor public class SignUpRequest { private String username; private String password; }
|
회원 정보를 저장하기 위한 Entity 생성
Account.java
@Data @NoArgsConstructor @AllArgsConstructor @Entity @Builder public class Account { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id;
@Column(unique = true) private String username;
private String password;
private Role role; }
|
Account를 저장하기 위한 Repository 생성
@Repository public interface AccountRepository extends JpaRepository<Account, String> { }
|
회원 가입 요청을 처리하기 위한 Service 생성
@Service @RequiredArgsConstructor public class AccountService {
private final AccountRepository accountRepository;
public Account saveAccount(SignUpRequest signUpRequest) { Account newAccount = Account.builder() .username(signUpRequest.getUsername()) .password(signUpRequest.getPassword()) .role(Role.USER) .build();
return accountRepository.save(newAccount); } }
|
Controller
회원가입에 필요한 Username과 Password를 갖고 /api/user/signup
에 Post 요청을 보내면 회원가입이 정상적으로 이루어진 경우 Status Code : 200이 반환되게 된다.
JwtController.java
@RestController @RequestMapping("/api/user") @RequiredArgsConstructor public class UserController {
private final AccountService accountService;
@PostMapping("/signup") public ResponseEntity signup(@RequestBody SignUpRequest signUpRequest){ accountService.saveAccount(signUpRequest); return ResponseEntity.ok().build(); } }
|