웹 프로그래밍

[Spring Boot] Licruit - 회원가입

미안하다 강림이 좀 늦었다 2024. 9. 10. 02:15

 

 

의존성 추가

build.gradle 파일에 DB 연결과 유효성 검사를 위해 아래 4개의 의존성을 추가했다.

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-web-services'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	implementation 'com.mysql:mysql-connector-j'
}

 

 

DB 연결 설정

application.properties 파일에 다음과 같이 DB 연결 설정을 한다.

처음에는 application.yml 파일을 만들어서 작성했었는데 자꾸 DB 연결을 못하길래 application.properties에 아래와 같이 작성하니까 해결됐다.

# Spring DataSource (MySQL)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/licruit?serverTimezone=Asia/Seoul&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=ncherryu

# Spring JPA
spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

 

 

DTO

request 객체를 정의한다. NotBlank 어노테이션은 유효성 검사 항목인데 아직 에러 처리를 어떻게 하는지 몰라서 일단 간단히만 적어두었다.

package com.example.licruitbackendjava.dto.user;

import jakarta.validation.constraints.NotBlank;
import lombok.Data;

@Data
public class RegisterDTO {

    @NotBlank(message = "사업자번호 확인 필요")
    private String companyNumber;

    @NotBlank(message = "비밀번호 확인 필요")
    private String password;

    @NotBlank(message = "상호명 확인 필요")
    private String businessName;

    @NotBlank(message = "연락처 확인 필요")
    private String contact;

    @NotBlank(message = "주소 확인 필요")
    private String address;

    @NotBlank(message = "업종 번호 확인 필요")
    private int sectorId;

    @NotBlank(message = "마케팅 동의 여부 확인 필요")
    private boolean isMarketing;
}

 

 

Entity

테이블에 대한 정보를 작성한다. length나 Size 등등 다른 것들도 나중에 더 지정해야 한다.

@Entity
@Setter
@Getter
@Table(name = "users")
public class UserEntity {

    @Id
    @Column(name = "company_number", length = 10)
    private String companyNumber;

    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "business_name", nullable = false)
    private String businessName;

    @Column(name = "contact", nullable = false)
    private String contact;

    @Column(name = "address", nullable = false)
    private String address;

    @Column(name = "sector_id", nullable = false)
    private int sectorId;

    @Column(name = "img", nullable = true)
    private String img;

    @Column(name = "is_marketing", nullable = false)
    private boolean isMarketing;

    public static UserEntity toUserEntity(RegisterDTO registerDTO) {
        UserEntity userEntity = new UserEntity();

        userEntity.setCompanyNumber(registerDTO.getCompanyNumber());
        userEntity.setPassword(registerDTO.getPassword());
        userEntity.setBusinessName(registerDTO.getBusinessName());
        userEntity.setContact(registerDTO.getContact());
        userEntity.setAddress(registerDTO.getAddress());
        userEntity.setSectorId(registerDTO.getSectorId());
        userEntity.setImg(null);
        userEntity.setMarketing(registerDTO.isMarketing());

        return userEntity;
    }
}

 

 

Controller

@Valid 어노테이션을 붙여서 유효성 검사를 해준다.

자동으로 400을 뱉어주는 줄 알았는데..... 그건 아닌 것 같아서 더 알아봐야 한다...

@RestController 말고 @Controller로 하니까 template 어쩌고를 못 찾는 에러가 나더라.

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @PostMapping("/register")
    public void addUser(@RequestBody @Valid RegisterDTO registerDTO) {
        userService.createUser(registerDTO);
    }
}

 

 

Service

repository에는 save라는 메소드가 자동으로 존재한다. save 메소드가 실행되면 DB에 저장된다.

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    public void createUser(RegisterDTO registerDTO) {
        UserEntity userEntity = UserEntity.toUserEntity(registerDTO);
        userRepository.save(userEntity);
    }
}

 

 

Repository

<위에서 만들었던 테이블 엔티티, PK 자료형>을 적으면 된다.

@Repository
public interface UserRepository extends JpaRepository<UserEntity, String> { 
    
}

 

 

주저리

1. 비밀번호 암호화 해야 함

2. 유효성 검사 결과 처리하는 방법 알아내야 함

3. 에러 처리하는 방법 알아내야 함

4. 응답 보내는 방법 알아내야 함

 

1번 하는 방법 찾아보다가 salt는 없어도 된다는 걸 알게되었다. 왜 그런지는... 더 찾아봐야 한다...

2번 하다보니까 express-validator가 천사라는 걸 느꼈다.

3번이랑 4번은 뭐 어떻게든 하면 될 것 같은데 정말 귀찮다...

 

결론: 오늘 한거라고는 DB 연결 ㅎㅎ