Back-End/Spring

[Spring] 예제 3 - 렌더링

09009 2023. 5. 25. 14:14

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	function checkValueAndSubmit() {
		const userIdBox = document.getElementById("userId");
		const idValue = userIdBox.value;
		
		const idRegEx = /^[a-zA-Z][a-zA-Z0-9]{4,12}$/;
		
		// idValue가 정규표현식에 적합하지 않으면
		if (!idRegEx.test(idValue)) {
			alert("아이디는 영소문자로 시작해야하고 영소문자, 대문자, 숫자로만 4~12글자이어야 합니다.");
			userIdBox.focus();
			return; // return;을 해줘야 submit이 발동되지 않는다. (주의!)
		}
		
		const userPwBox = document.getElementById("userPw");
		const userPwConfirmBox = document.getElementById("userPwConfirm");
		
		if(userPwBox.value != userPwConfirmBox.value) {
			alert("입력한 비밀번호를 다시 확인해주세요.")
			userPwBox.value = "";
			userPwConfirmBox.value = "";
			userPwBox.focus();
			return;
		}
		
		const pwRegEx = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[a-zA-Z\d!@#$%^&*()_+]{8,16}$/;
		
		if(!pwRegEx.test(userPwBox.value)){
			alert("비밀번호는.... 어쩌고 8-16 글짜.. 블라블라..");
			userPwBox.value = "";
			userPwConfirmBox.value = "";
			
			userPwBox.focus();
			return;
		}
		
		if(idChecked == false) {
			alert("아이디 중복확인을 해주세요");
			return;
		}
		
		const frm = document.getElementById("frm");
		frm.submit();
	}
	
	
	// 값이 중간에 바뀔 것이므로 const로 선언하면 안된다.
	let idChecked = false;
	
	function checkUserId() {
		
	    const userIdValue = document.getElementById("userId").value;
				
		// AJAX api 활용
		// 코드 실행 흐름 순서 중요
	    const xhr = new XMLHttpRequest(); // (1)
		
		// 이 값에 function을 넣을 수 있다. 콜백함수: 내가 만들었지만 내가 호출한 것이 아님.
	    xhr.onreadystatechange = function () { // (2)
			if(xhr.readyState == 4 && xhr.status == 200) {
				//(5)
				const response = JSON.parse(xhr.responseText);
				
				const idCheckAlert = document.getElementById("idCheckAlert");
				
				// js로 논리 코드 및 DOM 조작
				if(response.data == true) {
					idCheckAlert.innerText = "사용 불가능한 아이디입니다.";
					idChecked = false;
				} else {
					idCheckAlert.innerText = "사용 가능한 아이디입니다.";
					idChecked = true;
				}
				
			}		
		};
	    
	    xhr.open("get", "./existsUserId?userId=" + userIdValue);  // (3)  무엇을 호출할 것인지..? requestmapping 된 loginPage 접속
	    xhr.send(); // 콜백함수를 총 네 번 호출한다. // (4)
	}
	
</script>
</head>
<body>
<h1>회원 가입</h1>
<form id="frm" action="./registerProcess" method="post">
	ID: <input id="userId" type="text" name="user_id">
	<input onclick="checkUserId()" type="button" value="중복확인">
	<div id="idCheckAlert"></div>
	<br>
	PW: <input id="userPw" type="password" name="user_pw"><br>
	PW 확인: <input id="userPwConfirm" type="password"><br>
	nickname: <input type="text" name="nickname"><br>
	gender: 
	<input type="radio" name="gender" value="M">남
	<input type="radio" name="gender" value="F">여 <br>
	
	취미: 
	<c:forEach items="${hobbyList}" var="hobby">
		<input type="checkbox" name="hobby_id" value="${hobby.id}"> ${hobby.name}
	</c:forEach>
	
	<br>
	
	email: <input type="text" name="email"><br>
	생년월일: <input type="date" name="birth"><br>
	전화번호: <input type="text" name="phone"><br>
	<input type="button" value="회원가입" onclick="checkValueAndSubmit()">
	
</form>
<a href="./loginPage">로그인 페이지로 이동</a>
</body>
</html>

위와 같이 style로 지정하는 것보다 클래스화해서 css를 지정해주는 것이 더 바람직하다.

 

onblur 이벤트

글자를 작성하고 빠져나갔을 때

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	function checkValueAndSubmit() {
		const userIdBox = document.getElementById("userId");
		const idValue = userIdBox.value;
		
		const idRegEx = /^[a-zA-Z][a-zA-Z0-9]{4,12}$/;
		
		// idValue가 정규표현식에 적합하지 않으면
		if (!idRegEx.test(idValue)) {
			alert("아이디는 영소문자로 시작해야하고 영소문자, 대문자, 숫자로만 4~12글자이어야 합니다.");
			userIdBox.focus();
			return; // return;을 해줘야 submit이 발동되지 않는다. (주의!)
		}
		
		const userPwBox = document.getElementById("userPw");
		const userPwConfirmBox = document.getElementById("userPwConfirm");
		
		if(userPwBox.value != userPwConfirmBox.value) {
			alert("입력한 비밀번호를 다시 확인해주세요.")
			userPwBox.value = "";
			userPwConfirmBox.value = "";
			userPwBox.focus();
			return;
		}
		
		const pwRegEx = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[a-zA-Z\d!@#$%^&*()_+]{8,16}$/;
		
		if(!pwRegEx.test(userPwBox.value)){
			alert("비밀번호는.... 어쩌고 8-16 글짜.. 블라블라..");
			userPwBox.value = "";
			userPwConfirmBox.value = "";
			
			userPwBox.focus();
			return;
		}
		
		if(idChecked == false) {
			alert("아이디 중복확인을 해주세요");
			return;
		}
		
		const frm = document.getElementById("frm");
		frm.submit();
	}
	
	
	// 값이 중간에 바뀔 것이므로 const로 선언하면 안된다.
	let idChecked = false;
	
	function checkUserId() {
		
	    const userIdValue = document.getElementById("userId").value;
				
		// AJAX api 활용
		// 코드 실행 흐름 순서 중요
	    const xhr = new XMLHttpRequest(); // (1)
		
		// 이 값에 function을 넣을 수 있다. 콜백함수: 내가 만들었지만 내가 호출한 것이 아님.
	    xhr.onreadystatechange = function () { // (2)
			if(xhr.readyState == 4 && xhr.status == 200) {
				//(5)
				const response = JSON.parse(xhr.responseText);
				
				const idCheckAlert = document.getElementById("idCheckAlert");
				
				// js로 논리 코드 및 DOM 조작
				if(response.data == true) {
					idCheckAlert.style.color = "red";
					idCheckAlert.innerText = "사용 불가능한 아이디입니다.";
					idChecked = false;
				} else {
					idCheckAlert.style.color = "green";
					idCheckAlert.innerText = "사용 가능한 아이디입니다.";
					idChecked = true;
				}
				
			}		
		};
	    
	    xhr.open("get", "./existsUserId?userId=" + userIdValue);  // (3)  무엇을 호출할 것인지..? requestmapping 된 loginPage 접속
	    xhr.send(); // 콜백함수를 총 네 번 호출한다. // (4)
	}
	
</script>
</head>
<body>
<h1>회원 가입</h1>
<form id="frm" action="./registerProcess" method="post">
	ID: <input id="userId" type="text" name="user_id" onblur="checkUserId()">
	<%-- <input onclick="checkUserId()" type="button" value="중복확인">--%>
	<div id="idCheckAlert"></div>
	PW: <input id="userPw" type="password" name="user_pw"><br>
	PW 확인: <input id="userPwConfirm" type="password"><br>
	nickname: <input type="text" name="nickname"><br>
	gender: 
	<input type="radio" name="gender" value="M">남
	<input type="radio" name="gender" value="F">여 <br>
	
	취미: 
	<c:forEach items="${hobbyList}" var="hobby">
		<input type="checkbox" name="hobby_id" value="${hobby.id}"> ${hobby.name}
	</c:forEach>
	
	<br>
	
	email: <input type="text" name="email"><br>
	생년월일: <input type="date" name="birth"><br>
	전화번호: <input type="text" name="phone"><br>
	<input type="button" value="회원가입" onclick="checkValueAndSubmit()">
	
</form>
<a href="./loginPage">로그인 페이지로 이동</a>
</body>
</html>