본문 바로가기
study/Ajax

[Ajax] 26. Ajax를 이용하여 id 체크하기 [(회원가입)userEntry.jsp, AjaxController.java]

by 금이패런츠 2022. 5. 19.
728x90
반응형

userEntry.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%-- /springmvc1/src/main/webapp/WEB-INF/view/user/userEntry.jsp --%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<c:set var="path" value="${pageContext.request.contextPath }" /> <%-- /springmvc2 --%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사용자 등록</title>
<script type="text/javascript">
function idChk(id) {
	let result = document.querySelector("#result")
	//id.length : 입력된 userid의 길이
	if ((id.length < 3) || (id.length > 10)) {
		result.style.color='red'
		result.innerHTML="id는 3자리 이상 10자리 이하입니다."
	} else { //3자리 이상 10자리 이하인 경우
		$.ajax({
			url : "${path}/ajax/idchk",
			data : "userid=" + id,
			success : function(chk) {
				if (chk.trim() == 'false') {
					result.style.color='blue'
					result.innerHTML="사용 가능한 id 입니다."
				} else {
					result.style.color='red'
					result.innerHTML="사용중인 id 입니다."
				}
			}
		})
	}
}
</script>
</head>
<body>
	<h2>사용자 등록</h2>
	<div id="result"></div>
	<form:form modelAttribute="user" method="post" action="userEntry">
	<%-- global 오류 화면 출력 부분 --%>
		<spring:hasBindErrors name="user">
			<font color="red">
			<%--${errors.globalErrors } : Controller 에서 BindingResult.reject() 함수로 설정한 오류 --%>
			 <c:forEach items="${errors.globalErrors }"	var="error">
					<spring:message code="${error.code }" />
			 </c:forEach></font>
		</spring:hasBindErrors>
		
		<table border="1" style="border-collapse: collapse;">
			<tr>
				<td>아이디</td>
				<td><form:input path="userid" onkeyup="idChk(this.value)"/>
				   <font color="red"><form:errors path="userid" /></font></td>
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><form:password path="password" />
				 <font color="red"><form:errors	path="password" /></font></td>
			</tr>
			<tr>
				<td>이름</td>
				<td><form:input path="username" />
				 <font color="red"><form:errors	path="username" /></font></td>
			</tr>
			<tr>
				<td>전화번호</td>
				<td><form:input path="phoneno" />
				 <font color="red"><form:errors	path="phoneno" /></font></td>
			</tr>
			<tr>
				<td>우편번호</td>
				<td><form:input path="postcode" />
				 <font color="red"><form:errors	path="postcode" /></font></td>
			</tr>
			<tr>
				<td>주소</td>
				<td><form:input path="address" />
				 <font color="red"><form:errors	path="address" /></font></td>
			</tr>
			<tr>
				<td>이메일</td>
				<td><form:input path="email" />
				 <font color="red"><form:errors	path="email" /></font></td>
			</tr>
			<tr>
				<td>생년월일</td>
				<td><form:input path="birthday" />
				 <font color="red"><form:errors	path="birthday" /></font></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
				  <input type="submit" value="등록">
				  <input type="reset" value="초기화"></td>
			</tr>
		</table>
	</form:form>
</body>
</html>

AjaxController.java

package controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import logic.ShopService;
import logic.User;
/*
 * @Controller : @Component(객체화) + 요청을 받아주는 클래스
 * 		메서드 리턴타입 : String => 뷰의 이름 리턴
 * 		메서드 리턴타입 : ModelAndView => 뷰의 전달할 객체 + 뷰의 이름 리턴
 * 
 * @RestController : @Component(객체화) + 요청을 받아주는 클래스 + 클라이언트(브라우저)에 값을 뷰가 아닌 직접 전달
 * 		메서드 리턴타입 : String => 값 : 이전버전 @ResponseBody 기능
 * 		메서드 리턴타입 : Object => 값
 */
@RestController
@RequestMapping("ajax")
public class AjaxController {
	@Autowired
	ShopService service;
	
	@RequestMapping("idchk")
	public String idchk (String userid) {
		String chk = null;
		User user = service.userSelectOne(userid);
		if (user == null) chk = "false"; //등록된 회원이 없는 경우
		else chk = "true";
		return chk;
	}
	//produces : 클라이언트에 한글 인코딩 방식 설정
	//text/plain : 순수 문자열 (MIME 형식 : )
	@RequestMapping(value="select", produces="text/plain; charset=utf-8")
	public String select (String si, String gu, HttpServletRequest request) {
		BufferedReader fr = null;
		try {
			fr = new BufferedReader(new FileReader(request.getServletContext().getRealPath("/") + "file/sido.txt"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		Set<String> set = new LinkedHashSet<>(); //순서 유지 + 중복불가 가능한 Set객체
		String data = null;
		if (si == null && gu == null) {
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3) set.add(arr[0].trim());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (gu == null) { //si 파라미터 존재
			si = si.trim();
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3 && arr[0].equals(si) && !arr[0].equals(arr[1])) {
						set.add(arr[1].trim());
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { //si 파라미터 존재, gu 파라미터 존재
			si = si.trim();
			gu = gu.trim();
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3 && arr[0].trim().equals(si) && arr[1].trim().equals(gu) && !arr[1].equals(arr[2])) {
						if(arr.length > 3) arr[2] += " " + arr[3];
						set.add(arr[2].trim());
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		List<String> list = new ArrayList(set);
		return list.toString();
	}
}
728x90
반응형