관리 메뉴

거니의 velog

231005_AJAX 강의 본문

대덕인재개발원/대덕인재개발원_Front End

231005_AJAX 강의

Unlimited00 2023. 10. 5. 08:39

[join.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        <style>
        	input[type=button] {
        		margin: 5px;
        		border-radius: 30px;
        	}
        </style>
        <script>
            
            $(function(){
                
                $("#idChkBtn").on("click", function(){
                	// 입력한 값 가져오기
                	var idVal = $("#id").val().trim();
                	//console.log(idVal);
                	// 값의 형식 비교
                	var idreg = /^[a-z][a-zA-Z0-9]{3,7}$/;
                	if(!(idreg.test(idVal))) {
                		alert("id 형식 오류입니다...");
                		return false;
                	}
                	// 서버로 전송
                	$.ajax({
                		url : "<%= request.getContextPath() %>/idCheck.do",
                		data : { "id" : idVal },
                		type : "get",
                		success : function(res){
                			//console.log(res);
                			$("#idChkTxt").html(res.flag).css("color", "red");
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
                $("#zipBtn").on("click", function(){
                	window.open("searchDong.html", "우편번호찾기", "width=500 height=400");
                });
                
            });
            
        </script>
	</head>
	<body>
	<!-- 
		-- public String idDuplChk(String id)
		select mem_id from member where mem_id = 'a001';
		
		-- public List<ZipVO> selectByDong(String dong)
		select * from ziptb where dong like '탄방%';
		
		-- public int insertMember(MemberVO memVo);
		INSERT INTO member (
		    mem_id,
		    mem_pass,
		    mem_name,
		    mem_bir,
		    mem_zip,
		    mem_add1,
		    mem_add2,
		    mem_hp,
		    mem_mail
		) VALUES (
		    'xyz001',
		    '1234567',
		    '고릴라',
		    '1999-08-12',
		    '135-932',
		    '대전 서구 둔산동',
		    '222-2번지 대전경찰서 1층 원무과',
		    '010-1234-5678',
		    'kkk1234@ddit.or.kr'
		);
		
		commit;
	 -->
	<div class="container mt-3">
		<h2>회원가입</h2>
		<form>
			<div class="mb-3 mt-3 col-sm-4">
				<label for="id">아이디</label> 
				<input id="idChkBtn" type="button" class="btn btn-outline-success btn-sm" value="중복검사" />
				<span id="idChkTxt"></span>
				<input type="text" class="form-control" id="id" name="mem_id">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">이름</label> 
				<input type="text" class="form-control" id="name" name="mem_name">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">생년월일</label> 
				<input type="date" class="form-control" id="birth" name="mem_bir">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="pass">비밀번호</label> 
				<input type="password" class="form-control" id="pass" name="mem_pass">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="hp">전화번호</label> 
				<input type="text" class="form-control" id="hp" name="mem_hp">
			</div>
			<div class="mb-3 col-sm-4">
		        <label for="email">이메일</label>
		        <input type="email" class="form-control" id="email" name="mem_mail">
		    </div>
		    <div class="mb-3 col-sm-4">
				<label for="zip">우편번호</label> 
				<input id="zipBtn" type="button" class="btn btn-outline-info btn-sm" value="번호검색" />
				<input type="text" class="form-control" id="zip" name="mem_zip">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add1">주소</label> 
				<input type="text" class="form-control" id="add1" name="mem_add1">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add2">상세주소</label> 
				<input type="text" class="form-control" id="add2" name="mem_add2">
			</div>
			<button type="submit" class="btn btn-primary btn-lg">제출</button>
			<button type="submit" class="btn btn-secondary btn-lg">초기화</button>
		</form>
	</div>
</body>
</html>

[searchDong.html]

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
		<style>
            div {
                border: 3px dotted yellowgreen;
                margin: 20px;
                padding: 20px;
                font-size: 1.2rem;
                word-break: break-all;
            }
            input[type=button],
            button[type=button] {
                display: inline-block;
                padding: 5px 10px;
                text-align: center;
                font-size: 1.2em;
                font-weight: 700;
                background-color: blue;
                color: white;
                border: none;
                border-radius: 4px;
                margin-right: 10px;
                cursor: pointer;
            }
        </style>
		<script>
			/* $(function(){
				$("#btn1").click(function(){});
				
			}); */
			const proc1 = () => {
				var dongVal = $("#dong").val().trim();
				console.log(dongVal);
				
				if(dongVal.length < 1) {
					alert("동이름을 입력하세요.");
					return false;
				}
				
				var dongReg = /^[가-힣]+$/;
				
				if(!(dongReg.test(dongVal))) {
					alert("형식 오류입니다.");
					return false;
				}
				
				$.ajax({
					url : 'http://localhost/memberpro/selectByDong.do',
					data : { "dong" : dongVal },
					type : 'post',
					success : function(res){
						
					},
					error : function(xhr){
						alert("상태 : " + xhr.status);
					},
					dataType : 'json'
				});
				
			}
		</script>
	</head>
	<body>
		<p>찾는 동이름을 입력하세요</p>
		<input id="dong" type="text" />
		<input id="btn1" type="button" value="확인" onclick="proc1()" />
		
		<!-- <div id="result1"></div> -->
		<hr color="red" />
	</body>
</html>

[SelectByDong.java]

package kr.or.ddit.member.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.ZipVO;


@WebServlet("/selectByDong.do")
public class SelectByDong extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 전송데이터 받기 - data : { "dong" : dongVal }
		String dongVal = request.getParameter("dong");
		// service객체
		IMemberService service = MemberServiceImpl.getInstance();
		// service메소드 호출 - List
		List<ZipVO> zipList = service.selectByDong(dongVal);
		// list 결과를 request에 저장
		request.setAttribute("zipList", zipList);
		// jspview 페이지 설정 - forward
		request.getRequestDispatcher("/view/selectByDong.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

[selectByDong.jsp]

<%@page import="com.google.gson.Gson"%>
<%@page import="kr.or.ddit.member.vo.ZipVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	List<ZipVO> zipList = (List<ZipVO>) request.getAttribute("zipList");
	Gson gson = new Gson();
	String result = gson.toJson(zipList);
	out.print(result);
	out.flush(); // out 스트림에 남은 데이터를 밖으로 밀어냄.
%>

- http://localhost/memberpro/member/join.jsp


[searchDong.html]

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
		<style>
            div {
                border: 3px dotted yellowgreen;
                margin: 20px;
                padding: 20px;
                font-size: 1.2rem;
                word-break: break-all;
            }
            input[type=button],
            button[type=button] {
                display: inline-block;
                padding: 5px 10px;
                text-align: center;
                font-size: 1.2em;
                font-weight: 700;
                background-color: blue;
                color: white;
                border: none;
                border-radius: 4px;
                margin-right: 10px;
                cursor: pointer;
            }
            table tr:not(:first-of-type) {
            	cursor: pointer;
            }
        </style>
		<script>
		
			const proc1 = () => {
				var dongVal = $("#dong").val().trim();
				console.log(dongVal);
				
				if(dongVal.length < 1) {
					alert("동이름을 입력하세요.");
					return false;
				}
				
				var dongReg = /^[가-힣]+$/;
				
				if(!(dongReg.test(dongVal))) {
					alert("형식 오류입니다.");
					return false;
				}
				
				$.ajax({
					url : 'http://localhost/memberpro/selectByDong.do',
					data : { "dong" : dongVal },
					type : 'post',
					success : function(res){
						var code = "<table class='table table-dark table-hover'>";
						code += "<tr><th>우편번호</th><th>주소</th><th>번지</th></tr>";
						$.each(res, function(i, v){
							var bunji = v.bunji;
							if(!bunji) { // if(typeof bunji == "undefined")
								bunji = "";
							}
							code += `<tr class="ziptr"><td>${v.zipcode}</td>`;
							code += `<td>${v.sido} ${v.gugun} ${v.dong}</td>`;
							code += `<td>${bunji}</td></tr>`;
						});
						code += "</table>";
						
						$("#result1").html(code);
					},
					error : function(xhr){
						alert("상태 : " + xhr.status);
					},
					dataType : 'json'
				});
				
				$(function(){
					$(document).on("click", ".ziptr", function(){
						var thisIs = $(this);
						var zipCode = thisIs.find("td").eq(0).text().trim();
						//console.log(zipCode);
						var address = thisIs.find("td").eq(1).text().trim();
						//console.log(address);
						$('#zip', opener.document).val(zipCode);
						$('#add1', opener.document).val(address);
						
						window.close();
					});
				});
				
			}
		</script>
	</head>
	<body>
		<p>찾는 동이름을 입력하세요</p>
		<input id="dong" type="text" />
		<input id="btn1" type="button" value="확인" onclick="proc1()" />
		
		<div id="result1"></div>
		<hr color="red" />
	</body>
</html>

- http://localhost/memberpro/member/join.jsp


[InsertMember.java]

package kr.or.ddit.member.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;


@WebServlet("/insertMember.do")
public class InsertMember extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 전송데이터 받기 - data : data,
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String birth = request.getParameter("birth");
		String pass = request.getParameter("pass");
		String hp = request.getParameter("hp");
		String email = request.getParameter("email");
		String zip = request.getParameter("zip");
		String add1 = request.getParameter("add1");
		String add2 = request.getParameter("add2");
		// MemberVO객체 생성 후 집어넣기
		MemberVO memVo = new MemberVO();
		memVo.setMem_id(id);
		memVo.setMem_name(name);
		memVo.setMem_bir(birth);
		memVo.setMem_pass(pass);
		memVo.setMem_hp(hp);
		memVo.setMem_mail(email);
		memVo.setMem_zip(zip);
		memVo.setMem_add1(add1);
		memVo.setMem_add2(add2);
		// service객체
		IMemberService service = MemberServiceImpl.getInstance();
		// service메소드 호출 - int
		int memInsRes = service.insertMember(memVo);
		// int 결과를 request에 저장
		request.setAttribute("memInsRes", memInsRes);
		request.setAttribute("memNameInfo", name);
		// view 페이지 설정 - forward
		request.getRequestDispatcher("/view/insertMember.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

[InsertMember.java]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	// 서블릿에서 저장한 데이터 꺼내기
	int memInsRes = (int) request.getAttribute("memInsRes");
	String memNameInfo = (String) request.getAttribute("memNameInfo");
	if(memInsRes > 0){ // 성공
%>
		{
			"flag" : "ok",
			"msg" : "<%= memNameInfo %>님, 회원가입이 완료되었습니다."
		}
<%	
	}else { // 실패
%>
		{
			"flag" : "no",
			"msg" : "<%= memNameInfo %>님, 회원가입이 실패하였습니다."
		}
<%		
	}
%>

[join.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        <style>
        	input[type=button] {
        		margin: 5px;
        		border-radius: 30px;
        	}
        </style>
        <script>
            
            $(function(){
                
                $("#idChkBtn").on("click", function(){
                	// 입력한 값 가져오기
                	var idVal = $("#id").val().trim();
                	//console.log(idVal);
                	// 값의 형식 비교
                	var idreg = /^[a-z][a-zA-Z0-9]{3,7}$/;
                	if(!(idreg.test(idVal))) {
                		alert("id 형식 오류입니다...");
                		return false;
                	}
                	// 서버로 전송
                	$.ajax({
                		url : "<%= request.getContextPath() %>/idCheck.do",
                		data : { "id" : idVal },
                		type : "get",
                		success : function(res){
                			//console.log(res);
                			$("#idChkTxt").html(res.flag).css("color", "red");
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
                // 우편번호 검색
                $("#zipBtn").on("click", function(){
                	window.open("searchDong.html", "우편번호찾기", "width=500 height=400");
                });
                
                // 저장하기 - button type=submit인 경우
                // method와 action이 있는 경우 - button / submit
                // method와 action이 없는 경우 - button / submit
                /* $("#joinSubmitForm").on("submit", function(e){
                	// submit의 원래 고유 기능에 대한 이벤트를 제거한다.
                	e.preventDefault();
                	//alert("submit");
                }); */
                
             	// 저장하기 - button type=button인 경우
                $("#joinSubmitBtn").on("click", function(){
                	//alert("subBtn");
                	
                	// 입력한 모든 값을 가져온다.
                	// 공백, 형식 체크 - return false;
                	var idVal = $("#id").val().trim();
                	var nameVal = $("#name").val().trim();
                	var birthVal = $("#birth").val().trim();
                	var passVal = $("#pass").val().trim();
                	var hpVal = $("#hp").val().trim();
                	var emailVal = $("#email").val().trim();
                	var zipVal = $("#zip").val().trim();
                	var add1Val = $("#add1").val().trim();
                	var add2Val = $("#add2").val().trim();
                	
                	var data = { 
                		"id" : idVal,
                		"name" : nameVal,
                		"birth" : birthVal,
                		"pass" : passVal,
                		"hp" : hpVal,
                		"email" : emailVal,
                		"zip" : zipVal,
                		"add1" : add1Val,
                		"add2" : add2Val
                	};
                	
                	//console.log(data);
                	
                	$.ajax({
                		url : "<%= request.getContextPath() %>/insertMember.do",
                		data : data,
                		type : "post",
                		success : function(res){
                			if(res.flag == "ok"){
                				alert(res.msg);
                			}else{
                				alert(res.msg);
                			}
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
            });
            
        </script>
	</head>
	<body>
	<!-- 
		-- public String idDuplChk(String id)
		select mem_id from member where mem_id = 'a001';
		
		-- public List<ZipVO> selectByDong(String dong)
		select * from ziptb where dong like '탄방%';
		
		-- public int insertMember(MemberVO memVo);
		INSERT INTO member (
		    mem_id,
		    mem_pass,
		    mem_name,
		    mem_bir,
		    mem_zip,
		    mem_add1,
		    mem_add2,
		    mem_hp,
		    mem_mail
		) VALUES (
		    'xyz001',
		    '1234567',
		    '고릴라',
		    '1999-08-12',
		    '135-932',
		    '대전 서구 둔산동',
		    '222-2번지 대전경찰서 1층 원무과',
		    '010-1234-5678',
		    'kkk1234@ddit.or.kr'
		);
		
		commit;
	 -->
	<div class="container mt-3">
		<h2>회원가입</h2>
		<form id="joinSubmitForm">
			<div class="mb-3 mt-3 col-sm-4">
				<label for="id">아이디</label> 
				<input id="idChkBtn" type="button" class="btn btn-outline-success btn-sm" value="중복검사" />
				<span id="idChkTxt"></span>
				<input type="text" class="form-control" id="id" name="mem_id">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">이름</label> 
				<input type="text" class="form-control" id="name" name="mem_name">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">생년월일</label> 
				<input type="date" class="form-control" id="birth" name="mem_bir">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="pass">비밀번호</label> 
				<input type="password" class="form-control" id="pass" name="mem_pass">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="hp">전화번호</label> 
				<input type="text" class="form-control" id="hp" name="mem_hp">
			</div>
			<div class="mb-3 col-sm-4">
		        <label for="email">이메일</label>
		        <input type="email" class="form-control" id="email" name="mem_mail">
		    </div>
		    <div class="mb-3 col-sm-4">
				<label for="zip">우편번호</label> 
				<input id="zipBtn" type="button" class="btn btn-outline-info btn-sm" value="번호검색" />
				<input type="text" class="form-control" id="zip" name="mem_zip">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add1">주소</label> 
				<input type="text" class="form-control" id="add1" name="mem_add1">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add2">상세주소</label> 
				<input type="text" class="form-control" id="add2" name="mem_add2">
			</div>
			<!-- <button id="joinSubmit" type="submit" class="btn btn-primary btn-lg">제출</button> -->
			<button id="joinSubmitBtn" type="button" class="btn btn-primary btn-lg">submit</button>
			<button type="reset" class="btn btn-secondary btn-lg">초기화</button>
		</form>
	</div>
</body>
</html>

- http://localhost/memberpro/member/join.jsp


[join.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        <style>
        	input[type=button] {
        		margin: 5px;
        		border-radius: 30px;
        	}
        </style>
        <script>
            
            $(function(){
                
                $("#idChkBtn").on("click", function(){
                	// 입력한 값 가져오기
                	var idVal = $("#id").val().trim();
                	//console.log(idVal);
                	// 값의 형식 비교
                	var idreg = /^[a-z][a-zA-Z0-9]{3,7}$/;
                	if(!(idreg.test(idVal))) {
                		alert("id 형식 오류입니다...");
                		return false;
                	}
                	// 서버로 전송
                	$.ajax({
                		url : "<%= request.getContextPath() %>/idCheck.do",
                		data : { "id" : idVal },
                		type : "get",
                		success : function(res){
                			//console.log(res);
                			$("#idChkTxt").html(res.flag).css("color", "red");
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
                // 우편번호 검색
                $("#zipBtn").on("click", function(){
                	window.open("searchDong.html", "우편번호찾기", "width=500 height=400");
                });
                
                // 저장하기 - button type=submit인 경우
                // method와 action이 있는 경우 - button / submit
                // method와 action이 없는 경우 - button / submit
                /* $("#joinSubmitForm").on("submit", function(e){
                	// submit의 원래 고유 기능에 대한 이벤트를 제거한다.
                	e.preventDefault();
                	//alert("submit");
                }); */
                
             	// 저장하기 - button type=button인 경우
                $("#joinSubmitBtn").on("click", function(){
                	//alert("subBtn");
                	
                	/* // 입력한 모든 값을 가져온다.
                	// 공백, 형식 체크 - return false;
                	var idVal = $("#id").val().trim();
                	var nameVal = $("#name").val().trim();
                	var birthVal = $("#birth").val().trim();
                	var passVal = $("#pass").val().trim();
                	var hpVal = $("#hp").val().trim();
                	var emailVal = $("#email").val().trim();
                	var zipVal = $("#zip").val().trim();
                	var add1Val = $("#add1").val().trim();
                	var add2Val = $("#add2").val().trim();
                	
                	var data = { 
                		"id" : idVal,
                		"name" : nameVal,
                		"birth" : birthVal,
                		"pass" : passVal,
                		"hp" : hpVal,
                		"email" : emailVal,
                		"zip" : zipVal,
                		"add1" : add1Val,
                		"add2" : add2Val
                	}; */
                	
                	//console.log(data);
                	
                	var data = $("#joinSubmitForm").serializeArray();
                	console.log(data);
                	
                	<%-- $.ajax({
                		url : "<%= request.getContextPath() %>/insertMember.do",
                		data : data,
                		type : "post",
                		success : function(res){
                			if(res.flag == "ok"){
                				alert(res.msg);
                				location.href = "memberListView.do"; // 서블릿으로 가야 함.
                			}else{
                				alert(res.msg);
                			}
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	}); --%>
                });
                
            });
            
        </script>
	</head>
	<body>
	<!-- 
		-- public String idDuplChk(String id)
		select mem_id from member where mem_id = 'a001';
		
		-- public List<ZipVO> selectByDong(String dong)
		select * from ziptb where dong like '탄방%';
		
		-- public int insertMember(MemberVO memVo);
		INSERT INTO member (
		    mem_id,
		    mem_pass,
		    mem_name,
		    mem_bir,
		    mem_zip,
		    mem_add1,
		    mem_add2,
		    mem_hp,
		    mem_mail
		) VALUES (
		    'xyz001',
		    '1234567',
		    '고릴라',
		    '1999-08-12',
		    '135-932',
		    '대전 서구 둔산동',
		    '222-2번지 대전경찰서 1층 원무과',
		    '010-1234-5678',
		    'kkk1234@ddit.or.kr'
		);
		
		commit;
	 -->
	<div class="container mt-3">
		<h2>회원가입</h2>
		<form id="joinSubmitForm">
			<div class="mb-3 mt-3 col-sm-4">
				<label for="id">아이디</label> 
				<input id="idChkBtn" type="button" class="btn btn-outline-success btn-sm" value="중복검사" />
				<span id="idChkTxt"></span>
				<input type="text" class="form-control" id="id" name="mem_id">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">이름</label> 
				<input type="text" class="form-control" id="name" name="mem_name">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">생년월일</label> 
				<input type="date" class="form-control" id="birth" name="mem_bir">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="pass">비밀번호</label> 
				<input type="password" class="form-control" id="pass" name="mem_pass">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="hp">전화번호</label> 
				<input type="text" class="form-control" id="hp" name="mem_hp">
			</div>
			<div class="mb-3 col-sm-4">
		        <label for="email">이메일</label>
		        <input type="email" class="form-control" id="email" name="mem_mail">
		    </div>
		    <div class="mb-3 col-sm-4">
				<label for="zip">우편번호</label> 
				<input id="zipBtn" type="button" class="btn btn-outline-info btn-sm" value="번호검색" />
				<input type="text" class="form-control" id="zip" name="mem_zip">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add1">주소</label> 
				<input type="text" class="form-control" id="add1" name="mem_add1">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add2">상세주소</label> 
				<input type="text" class="form-control" id="add2" name="mem_add2">
			</div>
			<!-- <button id="joinSubmit" type="submit" class="btn btn-primary btn-lg">제출</button> -->
			<button id="joinSubmitBtn" type="button" class="btn btn-primary btn-lg">submit</button>
			<button type="reset" class="btn btn-secondary btn-lg">초기화</button>
		</form>
	</div>
</body>
</html>

- http://localhost/memberpro/member/join.jsp

[InsertMember.java]

package kr.or.ddit.member.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;


@WebServlet("/insertMember.do")
public class InsertMember extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 전송데이터 받기 - data : data,
//		String id = request.getParameter("id");
//		String name = request.getParameter("name");
//		String birth = request.getParameter("birth");
//		String pass = request.getParameter("pass");
//		String hp = request.getParameter("hp");
//		String email = request.getParameter("email");
//		String zip = request.getParameter("zip");
//		String add1 = request.getParameter("add1");
//		String add2 = request.getParameter("add2");
		// 전송데이터 받기 - data : data, 
		String id = request.getParameter("mem_id");
		String name = request.getParameter("mem_name");
		String birth = request.getParameter("mem_bir");
		String pass = request.getParameter("mem_pass");
		String hp = request.getParameter("mem_hp");
		String email = request.getParameter("mem_mail");
		String zip = request.getParameter("mem_zip");
		String add1 = request.getParameter("mem_add1");
		String add2 = request.getParameter("mem_add2");
		// MemberVO객체 생성 후 집어넣기
		MemberVO memVo = new MemberVO();
		memVo.setMem_id(id);
		memVo.setMem_name(name);
		memVo.setMem_bir(birth);
		memVo.setMem_pass(pass);
		memVo.setMem_hp(hp);
		memVo.setMem_mail(email);
		memVo.setMem_zip(zip);
		memVo.setMem_add1(add1);
		memVo.setMem_add2(add2);
		// service객체
		IMemberService service = MemberServiceImpl.getInstance();
		// service메소드 호출 - int
		int memInsRes = service.insertMember(memVo);
		// int 결과를 request에 저장
		request.setAttribute("memInsRes", memInsRes);
		request.setAttribute("memNameInfo", name);
		// view 페이지 설정 - forward
		request.getRequestDispatcher("/view/insertMember.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

[MemberListView.java]

package kr.or.ddit.member.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/memberListView.do")
public class MemberListView extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		out.println("<html lang='ko'>");
		out.println("<head><meta charset='utf-8' /><title>Request 객체 연습</title></head>");
		out.println("<body>");
		
		out.println("<h3>메인 페이지로 이동했습니다...</h3>");
		
		out.println("</body>");
		out.println("</html>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

[join.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <meta name="author" content="LeeGJ" />
        <meta name="copyright" content="대덕인재개발원" />
        <meta name="description" content="Ajax06" />
        <meta name="keywords" content="대덕인재개발원, html, Ajax06" />
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <title>Ajax06</title>
		<link href="../css/style07.css" rel="stylesheet" />
        <script src="../js/jquery-3.7.1.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
        <style>
        	input[type=button] {
        		margin: 5px;
        		border-radius: 30px;
        	}
        </style>
        <script>
            
            $(function(){
                
                $("#idChkBtn").on("click", function(){
                	// 입력한 값 가져오기
                	var idVal = $("#id").val().trim();
                	//console.log(idVal);
                	// 값의 형식 비교
                	var idreg = /^[a-z][a-zA-Z0-9]{3,7}$/;
                	if(!(idreg.test(idVal))) {
                		alert("id 형식 오류입니다...");
                		return false;
                	}
                	// 서버로 전송
                	$.ajax({
                		url : "<%= request.getContextPath() %>/idCheck.do",
                		data : { "id" : idVal },
                		type : "get",
                		success : function(res){
                			//console.log(res);
                			$("#idChkTxt").html(res.flag).css("color", "red");
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
                // 우편번호 검색
                $("#zipBtn").on("click", function(){
                	window.open("searchDong.html", "우편번호찾기", "width=500 height=400");
                });
                
                // 저장하기 - button type=submit인 경우
                // method와 action이 있는 경우 - button / submit
                // method와 action이 없는 경우 - button / submit
                /* $("#joinSubmitForm").on("submit", function(e){
                	// submit의 원래 고유 기능에 대한 이벤트를 제거한다.
                	e.preventDefault();
                	//alert("submit");
                }); */
                
             	// 저장하기 - button type=button인 경우
                $("#joinSubmitBtn").on("click", function(){
                	//alert("subBtn");
                	
                	/* // 입력한 모든 값을 가져온다.
                	// 공백, 형식 체크 - return false;
                	var idVal = $("#id").val().trim();
                	var nameVal = $("#name").val().trim();
                	var birthVal = $("#birth").val().trim();
                	var passVal = $("#pass").val().trim();
                	var hpVal = $("#hp").val().trim();
                	var emailVal = $("#email").val().trim();
                	var zipVal = $("#zip").val().trim();
                	var add1Val = $("#add1").val().trim();
                	var add2Val = $("#add2").val().trim();
                	
                	var data = { 
                		"id" : idVal,
                		"name" : nameVal,
                		"birth" : birthVal,
                		"pass" : passVal,
                		"hp" : hpVal,
                		"email" : emailVal,
                		"zip" : zipVal,
                		"add1" : add1Val,
                		"add2" : add2Val
                	}; */
                	
                	//console.log(data);
                	
                	var data = $("#joinSubmitForm").serializeArray();
                	console.log(data);
                	
                	$.ajax({
                		url : "<%= request.getContextPath() %>/insertMember.do",
                		data : data,
                		type : "post",
                		success : function(res){
                			if(res.flag == "ok"){
                				alert(res.msg);
                				location.href = "<%= request.getContextPath() %>/memberListView.do"; // 서블릿으로 가야 함.
                			}else{
                				alert(res.msg);
                			}
                		},
                		error : function(xhr){
                			alert("상태 : " + xhr.status);
                		},
                		dataType : "json"
                	});
                });
                
            });
            
        </script>
	</head>
	<body>
	<!-- 
		-- public String idDuplChk(String id)
		select mem_id from member where mem_id = 'a001';
		
		-- public List<ZipVO> selectByDong(String dong)
		select * from ziptb where dong like '탄방%';
		
		-- public int insertMember(MemberVO memVo);
		INSERT INTO member (
		    mem_id,
		    mem_pass,
		    mem_name,
		    mem_bir,
		    mem_zip,
		    mem_add1,
		    mem_add2,
		    mem_hp,
		    mem_mail
		) VALUES (
		    'xyz001',
		    '1234567',
		    '고릴라',
		    '1999-08-12',
		    '135-932',
		    '대전 서구 둔산동',
		    '222-2번지 대전경찰서 1층 원무과',
		    '010-1234-5678',
		    'kkk1234@ddit.or.kr'
		);
		
		commit;
	 -->
	<div class="container mt-3">
		<h2>회원가입</h2>
		<form id="joinSubmitForm">
			<div class="mb-3 mt-3 col-sm-4">
				<label for="id">아이디</label> 
				<input id="idChkBtn" type="button" class="btn btn-outline-success btn-sm" value="중복검사" />
				<span id="idChkTxt"></span>
				<input type="text" class="form-control" id="id" name="mem_id">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">이름</label> 
				<input type="text" class="form-control" id="name" name="mem_name">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="name">생년월일</label> 
				<input type="date" class="form-control" id="birth" name="mem_bir">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="pass">비밀번호</label> 
				<input type="password" class="form-control" id="pass" name="mem_pass">
			</div>
			<div class="mb-3 col-sm-4">
				<label for="hp">전화번호</label> 
				<input type="text" class="form-control" id="hp" name="mem_hp">
			</div>
			<div class="mb-3 col-sm-4">
		        <label for="email">이메일</label>
		        <input type="email" class="form-control" id="email" name="mem_mail">
		    </div>
		    <div class="mb-3 col-sm-4">
				<label for="zip">우편번호</label> 
				<input id="zipBtn" type="button" class="btn btn-outline-info btn-sm" value="번호검색" />
				<input type="text" class="form-control" id="zip" name="mem_zip">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add1">주소</label> 
				<input type="text" class="form-control" id="add1" name="mem_add1">
			</div>
		    <div class="mb-3 col-sm-6">
				<label for="add2">상세주소</label> 
				<input type="text" class="form-control" id="add2" name="mem_add2">
			</div>
			<!-- <button id="joinSubmit" type="submit" class="btn btn-primary btn-lg">제출</button> -->
			<button id="joinSubmitBtn" type="button" class="btn btn-primary btn-lg">submit</button>
			<button type="reset" class="btn btn-secondary btn-lg">초기화</button>
		</form>
	</div>
</body>
</html>

- http://localhost/memberpro/member/join.jsp

'대덕인재개발원 > 대덕인재개발원_Front End' 카테고리의 다른 글

231010_AJAX 강의  (0) 2023.10.10
231006_AJAX 강의  (0) 2023.10.06
231004_AJAX 강의  (0) 2023.10.02
230927_AJAX 강의  (0) 2023.09.27
230926_AJAX 강의  (0) 2023.09.26