[Web_3] Spring 8 πŸ‘Ώ

08627Β·2022λ…„ 9μ›” 26일
1

Spring

λͺ©λ‘ 보기
8/13
post-thumbnail


πŸ“Œ Request 데이터 DB Insert ν•˜κΈ° (2)

πŸ’‘ Request 데이터 DB Insert ν•˜κΈ° : User


πŸ‘Ύ EX. SignUp νšŒμ›κ°€μž…

▫️ PageController.java

@Controller
public class PageController {

    @GetMapping("/auth/signup")
    public String loadAuthSignup() {
        return "auth/signup";
    }
}

▫️ AuthController.java

@Slf4j
@RequiredArgsConstructor
@RestController
public class AuthController {

    private final UserRepository userRepository;

    // /api/auth/signup
    @PostMapping("/api/auth/signup")
    public ResponseEntity<?> signUp(UserSignUpReqDto userSignUpReqDto) {
        // formData 둜 λ“€μ–΄μ˜΄. -> HTML μƒμ—μ„œ DTO 둜 λ³€ν™˜μ„ μŠ€ν”„λ§μ΄ ν•΄μ£ΌλŠ”λ° κ·Έ λ•Œ Getter κ°€ ν•„μš”ν•¨.

        log.info("{}", userSignUpReqDto);

        User user = userSignUpReqDto.toEntity();



        log.info("λ§ˆμ΄λ°”ν‹°μŠ€ 보내지기 μ „ Entity: {}", user); // useGeneratedKeys λ₯Ό μ“°λ©΄ Auto increment 된 user code λ₯Ό λ°”λ‘œ κ°€μ Έλ‹€ μ“Έ 수 있게 λ˜λŠ” κ²ƒμž„.

        int result = userRepository.save(user);

        log.info("λ§ˆμ΄λ°”ν‹°μŠ€ 보내지고 λ‚˜μ„œ Entity: {}", user);


        UserSignUpRespDto userSignUpRespDto = user.toDto();


        if(result == 0) {
            return ResponseEntity.internalServerError().body(new CMRespDto<>(-1, "νšŒμ› κ°€μž… 였λ₯˜", null));
        }

        return ResponseEntity.ok(new CMRespDto<>(1, "νšŒμ› κ°€μž… μ™„λ£Œ", userSignUpRespDto));
    }
}

▫️ User.java

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
    private int user_code;
    private String user_id;
    private String user_password;
    private String user_name;
    private String user_email;

    public UserSignUpRespDto toDto() {
        return UserSignUpRespDto.builder()
                .userCode(user_code)
                .userId(user_id)
                .userPassword(user_password)
                .userName(user_name)
                .userEmail(user_email)

                .build();
    }
}

▫️ CMRespDto.java

@Data
@AllArgsConstructor
public class CMRespDto<T> {
    private int code;
    private String msg;
    private T data;
}

▫️ UserSignUpReqDto.java

@Data
public class UserSignUpReqDto {
    private String userId;
    private String userPassword;
    private String userName;
    private String userEmail;

    public User toEntity() {
        return User.builder()
                .user_id(userId)
                .user_password(userPassword)
                .user_name(userName)
                .user_email(userEmail)

                .build();
    }
}

▫️ UserSignUpRespDto.java

@Builder
@Data
public class UserSignUpRespDto {
    private int userCode;
    private String userId;
    private String userPassword;
    private String userName;
    private String userEmail;

}

▫️ UserRepository.java

@Mapper
public interface UserRepository {

    public int save(User user);

}

▫️ user.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.boot.mybatis20220923nk.repository.UserRepository">

    <insert id="save"
            parameterType="com.boot.mybatis20220923nk.domain.User"
            useGeneratedKeys="true"
            keyProperty="user_code"
    >
        <!-- select λΉΌκ³  insert update delete λŠ” 리턴이 영ν–₯받은 ν–‰ 수(int)둜 섀정해쀄 ν•„μš” μ—†μŒ. -->
        insert into
            user_mst
        values (
            0,
            #{user_id},
            #{user_password},
            #{user_name},
            #{user_email}
        )
    </insert>
</mapper>

▫️ signup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <style>
        ...
    </style>

</head>
<body>
    <div id="container">
        <form enctype="multipart/form-data">
            <table>
                <thead>
                    <tr>
                        <th colspan="2">
                            <h1>νšŒμ›κ°€μž…</h1>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th>
                            <label for="user-id">아이디</label>
                        </th>
                        <td>
                            <input type="text" id="user-id" name="userId">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="user-password">λΉ„λ°€λ²ˆν˜Έ</label>
                        </th>
                        <td>
                            <input type="password" id="user-password" name="userPassword">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="user-name">이름</label>
                        </th>
                        <td>
                            <input type="text" id="user-name" name="userName">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="user-email">이메일</label>
                        </th>
                        <td>
                            <input type="text" id="user-email" name="userEmail">
                        </td>
                    </tr>
                    
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="2">
                            <button type="button" class="signup-button">κ°€μž…ν•˜κΈ°</button>
                        </th>
                    </tr>
                </tfoot>
            </table>
        </form>
        
    </div>

    <script>
        const signupButton = document.querySelector(".signup-button");

        signupButton.onclick = () => {
            request();
        }

        function getFormData() {
            return new FormData(document.querySelector("form"));
        }

        function request() {

            $.ajax({
                async: false,
                type: "post",
                url: "/api/auth/signup",

                enctype: "multipart/form-data",
                contentType: false,
                processData: false,

                data: getFormData(),
                dataType: "json",
                success: (response) => {
                    alert(response.msg);
                    console.log(response);
                }, 
                error: (error) => {
                    console.log(error);
                    console.log(error.responseJSON.msg);
                }

            });
        }

    </script>
</body>
</html>

🦎

μ‚¬μš©μžκ°€ /auth/signup μ£Όμ†Œλ‘œ μ ‘μ†ν•˜κ²Œ 되면,
PageController μ—μ„œ html 화면을 λ„μ›Œμ€Œ.

μ‚¬μš©μžκ°€ ν•΄λ‹Ή 폼에 λ§žμΆ”μ–΄ 정보λ₯Ό μž…λ ₯ν•˜κ³  'κ°€μž…ν•˜κΈ°' λ²„νŠΌμ„ λˆ„λ₯΄λ©΄,
μž…λ ₯ν•œ 정보λ₯Ό 폼 데이터 ν˜•μ‹μœΌλ‘œ url /api/auth/signup 에 ajax둜 λ³΄λ‚΄κ²Œ λœλ‹€.

λ§€ν•‘λœ AuthController μ—μ„œ ν•΄λ‹Ή 폼 데이터λ₯Ό UserSignUpReqDto 둜 λ°›λŠ”λ‹€. (μŠ€ν”„λ§μ—μ„œ DTO둜 λ³€ν™˜ν•˜μ—¬ λ°›μ•„μ˜€λ„λ‘ 함)
그럼 AuthController μ—μ„œ DTO 둜 λ°›μ•„μ˜¨ 정보λ₯Ό User 객체둜 λ³€ν™˜ν•˜μ—¬ UserRepository(μ‹€μ œ λ°μ΄ν„°λ² μ΄μŠ€)에 User 정보λ₯Ό Insert ν•œλ‹€.

Insert κ°€ λ˜μ—ˆλŠ”μ§€μ˜ μ—¬λΆ€λ₯Ό ν΄λΌμ΄μ–ΈνŠΈμ— RespDto 둜 μ‘λ‹΅ν•œλ‹€.



πŸ“’ μ†Œκ° πŸ‘Ώ

0개의 λŒ“κΈ€