Frontend/AJAX
02. AJAX, 회원등록 아이디 중복 체크
개발개발빈이
2022. 6. 30. 22:48
○ 회원등록 아이디 중복 체크
1) 뷰단
<%@ 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.0.min.js"></script>
<script src="../js/jquery.cookie.js"></script>
</head>
<body>
<h3> 회원등록폼 </h3>
<form name="form1" method="post">
<table border="1" style="width:400px">
<tr>
<th>아이디</th>
<td>
<input type="text" name="userid" id="userid">
<input type="button" value="아이디중복확인" id="btn_userid">
<br>
<div id="panel" style="display:none"></div>
</td>
</tr>
</table>
</form>
<script>
//$.post("요청명령어", 전달값, callback함수)
$("#btn_userid").click(function(){
$.post(
"idcheckproc1.do" //요청명령어
, "userid=" + $("#userid").val() //전달값
, responseProc //콜백함수
);
}); //click() end
function responseProc(result){//result: 서버가 응답해준 메시지를 받는 변수
$("#panel").empty();
$("#panel").html(result);
$("#panel").show();
}//responseProc() end
</script>
</body>
</html>
2) 컨트롤러
//아이디 중복확인 페이지 불러오기
//결과확인 http://localhost:9095/member/idcheckform1.do
@RequestMapping("member/idcheckform1.do")
public String idCheckForm1() {
return "/member/idCheck";
}//idCheckForm1() end
@RequestMapping("member/idcheckproc1.do")
private void idCheckProc1(HttpServletRequest req, HttpServletResponse resp) {
try {
String userid=req.getParameter("userid").trim();
String message="";
if(userid.length()<5 || userid.length()>15) {
message="<span style='color:blue;font-weight:bold'>아이디는 5~15글자로 입력해 주세요</span>";
}else {
if(userid.equals("soldesk") || 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
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter out=resp.getWriter();
out.println(message);
out.flush();//out객체에 남아 있는 버퍼의 내용을 클리어
out.close();
}catch (Exception e) {
System.out.println("응답실패: " + e);
}
}//idcheckproc1() end
○ 회원등록 아이디 중복 체크 : 쿠키활용
- 쿠키를 활용하여 아이디 중복확인을 해야한 회원가입이 가능하도록
- 형식) $.cookie("쿠키변수명", 값)
① id=btn_userid 아이디중복확인 버튼을 클릭, 입력한 아이디를 변수에 대입하고 서버에 요청해서 응답받기
$("#btn_userid").click(function(){
var params="userid=" + $("#userid").val().trim();
//post방식으로 서버에 요청해서 응답받기
//①text응답
$.post("idcheckproc2.do", params, checkID, "text")
//②JSON응답
$.post("idcheckproc2.do", params, checkID, "json")
});
② 콜백함수 : 서버에서 응답받는 메시지(result)를 본문의 id=panel에 출력하기
function checkID(result){
//①text응답
//alert(result); //0또는 1
//②JSON응답
//alert(result); //[object Object] 또는 {"count":1}
//alert(result.count);
var count=eval(result.count); //형변환
if(count==0){
$("#panel").css("color", "blue");
$("#panel").text("사용 가능한 아이디입니다");
$.cookie("checkID", "PASS"); //아이디중복확인을 했다는 증거
}else{
$("#panel").css("color", "red");
$("#panel").text("이미 사용중인 아이디입니다");
$("#userid").focus(); //커서생성
}
}//checkID() end
③ 해당 페이지가 로딩되거나 검사 후 아이디 변경시 아이디중복확인과 관련된 쿠키변수 삭제
//해당 페이지가 로딩되었을 때 아이디중복확인과 관련된 쿠키변수 삭제
$(function(){
$.removeCookie("checkID");
});
//아이디 중복확인 후 아이디를 변경했을 시 쿠키삭제
$("#userid").change(function(){
$.removeCookie("checkID");
});
④ 아이디중복확인을 해야만 회원가입폼이 서버로 전송
function send() {
var checkID=$.cookie("checkID"); //쿠키변수값 가져오기
if(checkID=="PASS"){
return true; //서버로 전송
}else{
$("#panel").css("color", "green");
$("#panel").text("아이디 중복 확인을 해주세요");
$("#userid").focus(); //커서생성
return false;
}//if end
}//send() end
⑤ 전체 소스
<%@ 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.0.min.js"></script>
<script src="../js/jquery.cookie.js"></script>
</head>
<body>
<h3> 회원등록폼(cookie) </h3>
<form name="memfrm" method="post" action="insert.do" onsubmit="return send()">
<table border="1" style="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>
$(function(){
$.removeCookie("checkID");
}); //end
$("#btn_userid").click(function(){
var params="userid=" + $("#userid").val().trim();
$.post("idcheckproc2.do", params, checkID, "json")
});
function checkID(result){
var count=eval(result.count);
if(count==0){
$("#panel").css("color", "blue");
$("#panel").text("사용 가능한 아이디입니다");
$.cookie("checkID", "PASS");
}else{
$("#panel").css("color", "red");
$("#panel").text("이미 사용중인 아이디입니다");
$("#userid").focus();
}
}//checkID() end
$("#userid").change(function(){
$.removeCookie("checkID");
});
function send() {
var checkID=$.cookie("checkID");
if(checkID=="PASS"){
return true;
}else{
$("#panel").css("color", "green");
$("#panel").text("아이디 중복 확인을 해주세요");
$("#userid").focus();
return false;
}//if end
}//send() end
</script>
</body>
</html>
⑥ 컨트롤러
//결과확인 http://localhost:9095/member/idcheckform2.do
@RequestMapping("member/idcheckform2.do")
public String idCheckForm2() {
return "/member/idCheck_cookie";
}//idCheckForm1() end
@RequestMapping("member/idcheckproc2.do")
private void idCheckProc2(HttpServletRequest req, HttpServletResponse resp) {
try {
String userid=req.getParameter("userid").trim();
int cnt=0;
if(userid.equals("soldesk") || userid.equals("webmaster")) {
cnt=1; //아이디가 중복되었다면
}
/*
//1)text응답
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter out=resp.getWriter();
out.println(cnt);
out.flush();//out객체에 남아 있는 버퍼의 내용을 클리어
out.close();
*/
//2)JSON응답
//https://mvnrepository.com에서 json-simple검색후, pom.xml에 의존성 추가해야 함
JSONObject json=new JSONObject();
json.put("count", cnt); //key, value
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter out=resp.getWriter();
out.println(json.toString());
out.flush();//out객체에 남아 있는 버퍼의 내용을 클리어
out.close();
} catch (Exception e) {
System.out.println("아이디중복확인 쿠키 실패 : " + e);
}
}//idcheckproc2() end