본문 바로가기
공부/Spring

[Spring] 회원가입페이지 만들기 ( Ajax을 이용한 아이디 중복체크 구현)

by students 2022. 9. 5.

이전 시간에 만들었던 회원가입 페이지에  Ajax를 이용해서 아이디 중복 체크 기능을 구현해보자

 

1. Ajax란?

Ajax란 Asynchronous JavaScript and XML의 약자입니다.

Ajax는 빠르게 동작하는 동적인 웹 페이지를 만들기 위한 개발 기법의 하나입니다.

 

Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다.

즉 Ajax를 이용하면 백그라운드 영역에서 서버와 통신하여, 그 결과를 웹 페이지의 일부분에만 표시할 수 있습니다.

 

이때 서버와는 다음과 같은 다양한 형태의 데이터를 주고받을 수 있습니다.

 

 - JSON

 - XML

 - HTML

 - 텍스트 파일 등

 

2. Ajax의 장점

Ajax를 이용하면 다음과 같은 장점이 있습니다.

 

1. 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다.

2. 웹 페이지가 로드된 후에 서버로 데이터 요청을 보낼 수 있습니다.

3. 웹 페이지가 로드된 후에 서버로부터 데이터를 받을 수 있습니다.

4. 백그라운드 영역에서 서버로 데이터를 보낼 수 있습니다.

 


1) 파일 및 패키지 생성

2-1. RestUserController.java 생성

1
2
3
4
5
6
7
8
9
10
11
12
package com.spring.example.user.controller;
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/user/*")
 
public class RestUserController {
 
}
 
cs

2-2. RestUserController.java("checkId")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
    @Autowired
    private UserService userService;
    
    @RequestMapping("checkId")
    public HashMap<String, Object> checkId (String user_id) {
        
        HashMap<String, Object> data = new HashMap<String, Object>();
        
        int Count = userService.checkId(user_id);
        
        if ( Count == 0 ) {
            data.put("result""success");
        } else {
            data.put("result""fail");
        }
        
        return data;
    }
    
cs

2-3. joinUserPage.js 파일 생성 (src\main\webapp\resources/js 풀더 안에 생성)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * 
 */
window.addEventListener("DOMContentLoaded"function () {
    $("#checkIdButton").click(function () {
        var value = $("#joinIdInput").val();
 
        if (value.replace(/\s| /gi, "").length == 0) {
            $("#alertId").css({
                "color""red"
            });
            $("#alertId").text("!  아이디를 입력해주세요.")
            return;
        }
    
        $.ajax({
            type: "get",
            url: "./checkId",
            data: {
                user_id: $("#joinIdInput").val()
            },
            dataType: "json",
            //contentType : "application/x-www-form-urlencoded", // post
            success: function (data) {
                if (data.result == "fail") {
                    $("#alertId").css({
                        "color""red"
                    });
                    $("#alertId").text("! 이미 사용중인 아이디입니다.")
                } else {
                    $("#alertId").css({
                        "color""black"
                    });
                    $("#alertId").text("✔  사용 가능한 아이디입니다.")
                    }
                }
        });        
    });
    
});
cs

5 ~ 38행 : id가 checkIdButteon 인 객체를 눌럿을때 실행될 메서드

6행 : id가 joinIdInput인 객체의 값을 value 라는 변수안에 값을 저장한다 

8 ~ 14행 : 변수 value 값이 null 인지 체크 한후 null 일 경우 #alertId 객체의 css 속성과 text를 바꾼다

16 ~ 37행 : ajax 호출 부분이다.

3) joinUserPage.jsp 

1
2
3
4
5
6
7
8
9
10
                                <div class="row mt-3">
                                    <div class="inputTitle">아이디</div>
                                    <div class="col-3 fs-5"><form:input class="form-control" id="joinIdInput" path="user_id"
                                            type="text" placeholder="아이디를 입력해 주세요." aria-label="default input example" />
                                            <form:errors path="user_id" id="error_message" />
                                    </div>
                                    <div class="col-2 d-grid"><button type="button" id="checkIdButton" class="btnBasic"
                                            style="height:36px;">중복확인</button></div>
                                    <div class="col my-auto" id="alertId"></div>
                                </div>
cs

 

4) UserSQLMapper.xml

1
2
3
    <select id="checkId" resultType="int">
        SELECT count(*FROM EXAMPLE_USER WHERE user_id = #{user_id}
    </select>
cs

 

5) 실행결과

 

실행 이후에 중복 확인 버튼 눌럿을떄 존재 하는 아이디라면 이미 사용중인 아이디입니다. 존재 하지 않는 아이디라면

사용 가능한 아이디입니다. 라고 문구가 출력되면 정상적으로 ajax로 아이디 중복체크가 됏다

 

이제 아이디 중복체크를 기능을 참고해서 다른 중복체크 기능도 구현해봐야지 !!..

댓글