⁂ AJAX/: 기본 익히기

[AJAX] #3 - ajax로 ID 중복확인 하기(쿠키 사용)

김갱환 2022. 11. 9. 17:38

1. ID 중복확인하기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>idCheck.jsp</title>
	<script src="../js/jquery-3.6.1.min.js"></script>
	<script src="../js/jquery.cookie.js"></script>
</head>
<body>
	
	<h3>회원 등록 폼</h3>
	<form name="memfrm">
		<table border="1" width="400px">
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" id="userid">
				<input type="button" value="아이디중복확인" id="btn_userid">    
				<br>
				<div id="panel" style="display:none"></div>
			</td>
		</tr>
		</table>
	</form>

</body>
</html>

 

 아이디 중복확인 버튼을 누르면 panel 이란 아이디를 가진 div 공간에 중복확인 결과를 출력 시켜보자.

 

1) $.post() / $.serialize() : 아이디 중복확인하기

 

- 형식

$.post("요청명령어",전달값,callback함수)

 

- 구현 1) : jsp 페이지 코딩

$("#btn_userid").click(function(){
    $.post(
             "idcheckproc.do"				// 요청 명령어
            ,"userid="+ $("#userid").val()	// 전달값
            ,responseProc					// 콜백함수
            );
}); // click() end

function responseProc(result){
    $("#panel").empty();
    $("#panel").html(result);
    $("#panel").show();
}; // responseProc() end

 

- 구현 2) : 컨트롤러 생성

// 아이디 중복확인 페이지 불러오기
// 결과 확인 http://localhost:9095/member/idcheckform.do
@RequestMapping("idcheckform.do")
public String idCheckForm() {
    return "/member/idCheck";
} // idCheckForm() end

@ResponseBody
@RequestMapping("idcheckproc.do")
public String idCheckProc(HttpServletRequest req) {
    String userid = req.getParameter("userid");
    String message = "";

    if(userid.length()<5 || userid.length()>15) {
        message = "<span style='color:blue;font-weight:bold;'>아이디는 5~15글자 이내로 입력해주세요!</span>";
    } else {
        if(userid.equals("itwill") || userid.equals("webmaster")) {
            message = "<span style='color:red;font-weight:bold;'>중복된 아이디입니다!</span>";
        } else {
            message = "<span style='color:green;font-weight:bold;'>사용 가능한 아이디입니다</span>";
        } // if end			
    } // if end
    return message;
} // idCheckProc() end

 

 

2) cookie : 중복확인을 한 아이디의 쿠키를 저장하여 회원가입 페이지로 연결시키게 하기

 우리는 회원가입을 할 때 중복확인을 통과한 사람만 회원가입을 진행할 수 있게 하려 한다.

 이 때 위의 과정을 통해 사용자가 중복확인을 눌러서 사용가능한 아이디라는 결과를 받은 값을 쿠키로 저장하는 것이 필요하다.

 

 jQuery에서는 이 쿠키를 손쉽게 사용할 수 있도록 구현해두었기에 이를 잘 사용해보고자 한다.

 

- 구현 1) : JSP 페이지

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>idCheck_cookie.jsp</title>
	<script src="../js/jquery-3.6.1.min.js"></script>
	<script src="../js/jquery.cookie.js"></script>
</head>
<body>
	<!-- 쿠키를 활용하여 아이디 중복확인을 해야만 회원가입이 가능하다 -->	
	<h3>회원 등록 폼(cookie)</h3>
	
	<form>
		<table border="1" width="400px">
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" name="userid" id="userid">
				<input type="button" value="아이디중복확인" id="btn_userid">
				<br>
				<span id="panel"></span><!-- 아이디 중복 관련 메세지 -->
			</td>
		</tr>
		<tr>
			<th>비밀번호</th>
			<td><input type="password" name="passwd"></td>
		</tr>
		<tr>
			<th>이름</th>
			<td><input type="text" name="name"></td>
		</tr>
		<tr>
			<th>이메일</th>
			<td><input type="text" name="email"></td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<input type="submit" value="회원가입">
			</td>
		</tr>
		</table>
	</form>

	<script>
	// 1) id="btn_userid" 아이디 중복확인 버튼이 클릭 되었을 때
	$("#btn_userid").click(function(){
		// 2) 입력한 id="btn_userid" 값을 변수에 대입하기
		let params = "userid=" + $("#userid").val().trim();
		
		// 3) post 방식으로 서버에 요청해서 응답받기
		//  -> 형식 : $.post("요청 명렁어", 전달값, 콜백함수, 응답 받는 형식)
	    $.post("idcheckcookieproc.do", params, checkID, "text");
		
		
	}); // click() end

	// 4) 콜백 함수
	function checkID(result){
	    alert(result);
	} // checkID() end
	</script>

</body>
</html>

 

 

- 구현 2) : 컨트롤러 생성

// 쿠키를 활용하여 아이디를 중복확인해야만 회원가입을 할 수 있다.
// 결과 확인 http://localhost:9095/member/idcheckcookieform.do
@RequestMapping("idcheckcookieform.do")
public String idcheckcookieform() {
    return "/member/idCheck_cookie";
} // idcheckcookieform() end

@ResponseBody
@RequestMapping("idcheckcookieproc.do")
public String idCheckCookieProc(HttpServletRequest req) {
    String userid = req.getParameter("userid").trim();

    String cnt = "0";
    if(userid.equals("itwill") || userid.equals("webmaster")) {
        cnt = "1";
    } // if end
    return cnt;

} // idCheckCookieProc() end

 

- 구현 3) : JSON으로 접근하기

여기서 return값을 int로 줘도 무방하지만 JSON을 사용하여 응답하는 것도 가능하기에 이를 확인하고자 String 값을 주었다.

 

 - .jsp 페이지 수정

    // ② JSON 응답
    $.post("idcheckcookieproc.do", params, checkID, "json");

 

 - 컨트롤러 수정

//		2) JSON 응답-----------------------------------------------------
//		https://mvnrepository.com에서 json-simple 검색 후 pom.xml에 의존성을 추가해야 한다.
JSONObject json = new JSONObject();
json.put("count", cnt); // Key, Value
return json.toString();

 

 - 콜백 함수 checkID() 수정

// 		② json 응답
alert(result); // [object Object] 또는 {"count":1} 
alert(result.count); // 0 또는 1

 

 

- 구현 4) : 쿠키에 아이디 저장하기

 콜백 함수인 checkID() 수정

// 5) 서버에서 응답받는 메세지(result)를 본문의 id=panel에 출력하고, 쿠키변수를 저장
// 	형식 : $.cookie("쿠키변수명", 값)
let count = eval(result.count); // 형변환
if(count==0){
    $("#panel").css("color", "blue");
    $("#panel").text("사용 가능한 아이디 입니다");
} else {
    $("#panel").css("color", "red");
    $("#panel").text("중복된 아이디 입니다");
} // if end

 

- <form>의 속성 추가

<form name="memfrm" method="post" action="./insert.do" onsubmit="return send()">

 

- function 추가 1) 페이지를 리로딩하면 쿠키 삭제하기 : 만약 중복확인은 했으나 페이지를 새로 불러서 새로운 아이디를 쓸 수도 있기 때문에

// 6) 해당 페이지가 로딩되었을 때 아이디 중복확인과 관련된 쿠키를 삭제해주기
$(function (){
    $.removeCookie("checkID");		
}); // end

 

- function 추가 2) 아이디 중복확인을 해야만 회원가입폼이 서버로 전송

// 7) 아이디 중복확인을 해야만 회원가입폼이 서버로 전송
function send() {
    // 아이디 입력했는지?
    if($("#userid").val()==""){
        alert("아이디를 입력해주세요")
        $("#userid").focus();
        return false;
    } // if end

    // 비밀번호 입력했는지?
    if($("#passwd").val()==""){
        alert("비밀번호를 입력해주세요")
        $("#passwd").focus();
        return false;
    } // if end

    // 이름 입력했는지?
    if($("#name").val()==""){
        alert("이름을 입력해주세요")
        $("#name").focus();
        return false;
    } // if end

    // 이메일 입력했는지?
    if($("#email").val()==""){
        alert("이메일을 입력해주세요")
        $("#email").focus();
        return false;
    } // if end

    // 아이디 중복확인 했는지
    let checkID = $.cookie("checkID"); // 쿠키값 가져오기
    if(checkID=="PASS"){
        return true;
    } else {
        $("#panel").css("color", "green");
        $("#panel").text("아이디 중복 확인 해주세요");
        $("#userid").focus();
        return false;
    } // if end

} // send() end

 

 

3) insert.do 명령어를 사용하여 콘솔창에 결과 출력시키기

@RequestMapping(value = "insert.do", method = RequestMethod.POST)
public void insert(HttpServletRequest req) {

    System.out.println("아이디 : " + req.getParameter("userid"));
    System.out.println("비번 : " + req.getParameter("passwd"));
    System.out.println("이름 : " + req.getParameter("name"));
    System.out.println("이메일 : " + req.getParameter("email"));

} // insert() end

 

입력한 결과값이 잘 넘어온다