웹개발 교육/Spring

[73일] Spring (15) - Ajax 아이디 중복 확인(cookie)

2022. 11. 9. 17:14

생성

idCheck.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<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>
	
	<script>
	
	//$.post("요청명령어", 전달값, callback함수)
	$("#btn_userid").click(function(){
		$.post(
				  "idcheckproc.do"					//요청명령어
				, "userid=" + $("#userid").val()	//전달값
				, responseProc						//콜백함수
			  );
	});//click() end
	
	function responseProc(result){ //result:서버가 응답해준 메시지를 받는 변수
		$("#panel").empty();
		$("#panel").html(result);
		$("#panel").show();
	}//responseProc() end
	
	</script>
</body>
</html>

 

패키지와 클래스 생성

 

MemberCont.java

package kr.co.itwill.member;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/member")
public class MemberCont {

	public MemberCont() {
		System.out.println("-----MemberCont()객체 생성 됨");
	}//end
	
	//아이디 중복확인 페이지 불러오기
	//결과확인 http://localhost:9095/member/idcheckform.do
	@RequestMapping("idcheckform.do")
	public String idCheckForm() {
		return "member/idCheck";
	}//idCheckForm() end
	
}//class end

 

 

	@RequestMapping("idcheckproc.do")
	@ResponseBody
	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

 

 

아이디 중복확인 여부까지 확인하기에는 서버는 너무 바쁘다. 따라서 사용자 pc의 쿠키를 통해 확인한다.

 

idCheck_cookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<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>
	
	</script>
</body>
</html>

 

MemberCont.java

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

idCheck_cookie.jsp

	<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>

 

MemberCont.java

	@RequestMapping("idcheckcookieproc.do")
	@ResponseBody
	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

 

 

 

idCheck_cookie.jsp

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

 

 

MemberCont.java

	@RequestMapping("idcheckcookieproc.do")
	@ResponseBody
	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
		
		//1)text 응답-------------------------------------------------
		
		//return cnt;
		
		//2)JSON 응답-------------------------------------------------
		//https://mvnrepository.com에서 json-simple 검색 후, pom.xml에 의존성 추가해야 함
		JSONObject json = new JSONObject();
		json.put("count", cnt);
		return json.toString();
		
	}//idCheckCookieProc() end

 

 

 

idCheck_cookie.jsp

수정

 

	<script>
	
		//6) 해당 페이지가 로딩되었을 때 아이디 중복 확인과 관련된 쿠키변수 삭제
		$(function(){
			$.removeCookie("checkID");
		});//end
	
		
		//1) id="btn_userid" 아이디 중복 확인 버튼을 클릭했을 때
		$("#btn_userid").click(function(){
			//2) 입력한 id="btn_userid" 값을 변수에 대입하기
			let params = "userid=" + $("#userid").val().trim();
		
			//3)post방식으로 서버에 요청해서 응답받기
			//형식) $.post("요청명령어", 전달값, 콜백함수, 응답받는형식)
			
			//① text 응답
			//$.post("idcheckcookieproc.do", params, checkID, "text");
			
			//② JSON 응답
			$.post("idcheckcookieproc.do", params, checkID, "json");
		});//click() end
		
		//4) 콜백함수
		function checkID(result){
			
			//① text 응답
			//alert(result); //0 또는 1
			
			//② JSON 응답
			//alert(result); //[object Object] 또는 {"count":1}
			//alert(result.count);
			
			//5)서버에서 응답받는 메시지(result)를 본문의 id=panel에 출력하고
			//  쿠키변수에 저장
			//  형식) $.cookie("쿠키변수명", 값)
			let 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;
			}//if end
		}//checkID() end
		
		
		//7)아이디 중복 확인을 해야만 회원가입 폼이 서버로 전송
		function send() {
			//아이디 입력했는가?
			//비밀번호 입력했는가?
			//이름 입력했는가?
			//이메일 입력했는가?
					
			//아이디 중복확인 했는가?
			let checkID = $.cookie("checkID"); //쿠키변수값 가져오기
			if(checkID=="PASS") {
				return true; //서버로 전송
			} else {
				$("#panel").css("color", "green");
				$("#panel").text("아이디 중복 확인 해주세요");
				$("#userid").focus;
			}//if end
		}//send() end
		
	</script>

 

 

중복확인 안했을 때
중복확인 했을 때

 

 

MemberCont.java

	@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

 

'웹개발 교육 > Spring' 카테고리의 다른 글

[74일] Spring (17) - Ajax 검색  (0) 2022.11.10
[73일] Spring (16) - Ajax 이미지 출력  (0) 2022.11.09
[73일] Spring (14) Ajax - 서버에서 응답 받기  (0) 2022.11.09
[71일] spring (13) - mymelon 호스팅  (0) 2022.11.07
[70일] spring (12) - mymelon media 수정  (0) 2022.11.04
'웹개발 교육/Spring' 카테고리의 다른 글
  • [74일] Spring (17) - Ajax 검색
  • [73일] Spring (16) - Ajax 이미지 출력
  • [73일] Spring (14) Ajax - 서버에서 응답 받기
  • [71일] spring (13) - mymelon 호스팅
ewok
ewok
ewok
기록장
ewok
전체
오늘
어제
  • 분류 전체보기
    • 웹개발 교육
      • HTML
      • CSS
      • JavaScript
      • Database
      • Java
      • jQuery
      • Ajax
      • Bootstrap
      • jsp
      • Spring
      • MyBatis
      • 프로젝트
    • JAVA
    • SpringBoot
      • 기초
      • AWS
      • 개인프로젝트
    • Spring Security
    • JPA
    • 테스트코드
    • Error
    • CS
      • 컴퓨터 구조
      • 이산수학
    • 알고리즘
      • 정리
      • Java
    • SQL
    • 자격증
      • SQLD
      • 정보처리기사
    • Git

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • GIT
  • branch
  • org.hibernate.tool.schema.spi.CommandAcceptanceException
  • sqld 합격
  • 버전 관리
  • 생성자
  • SQLD
  • merge commit
  • org.springframework.beans.factory.UnsatisfiedDependencyException
  • this
  • sqld 자격증
  • 노랭이
  • git bash
  • base
  • 브랜치

최근 댓글

최근 글

hELLO · Designed By 정상우.
ewok
[73일] Spring (15) - Ajax 아이디 중복 확인(cookie)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.