본문 바로가기
개발 공부 Today I Learned

[국비 41일차 TIL] jQuery jsp 회원가입, id 중복확인

by 개발자신입 2024. 1. 18.
반응형

 

 

 

jQuery 사용을 위한 시작 스크립트 (외워!)

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		
		alert("jQuery가 동작합니다.");
	}); 
</script>

 

 

join.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- jstl을 쓰기 위한 코어태그 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>가입 시 무료 쿠폰 증정!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="./css/index.css" rel="stylesheet">
<link href="./css/menu.css" rel="stylesheet">
<script type="text/javascript" src="./js/menu.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.min.js"></script>

<script type="text/javascript">
//	$(document).ready(function (){ // 첫 문서가 로딩될 때 기능 실행
//		$('.id-alert').hide(); 
//	});

// 아래는 위의 코드와 같음. 다른 모양.
	$(function (){
		$('.id-alert, .name-alert, .pw-alert').hide();
	});
	
		// $(선택자).할일();
		function check() {
		let id = $("#id").val();
		if(id.length < 3 || id == ""){
			$('.id-alert').show();
			$("#id").focus();
			return false;
		}
		$('.id-alert').hide();
		
		let name=$('#name').val();
		if(name.length < 2){
			$('.name-alert').show();
			$('#name').focus();
			return false;
		}
		$('.name-alert').hide();
		
		let pw1 = $('#pw1').val();
		let pw2 = $('#pw2').val();
		if(pw1.length < 8){
			alert("암호는 8글자 이상이어야 합니다.")
			$('#pw1').focus();
			return false;
		}

		if(pw1 != pw2){
			alert("암호가 일치하지 않습니다.")
			return false;
		}
		if(pw1 != pw2){
			$('.pw-alert').show();
			$('#pw2').val("");
			$('#pw2').focus();
			return false;
		}
		$('.pw-alert').hide();
	}
		
	function idCheck(){
//		alert('ID 중복검사');

		let id = $('#id').val();
		
		const regExp = /[ㄱ-ㅎㅏ-ㅣ가-힣]/g;
		if(id.length < 4 || regExp.test(id)){
			alert("아이디는 영문자 4글자 이상이어야 합니다.")
			$('#id').focus();
		
		} else {
			// AJAX = 1. 페이징, 2. AJAX, 3. 파일 업로드
			$.ajax({
				url : './idCheck',
				type : 'post',
				dataType : 'text',
				data : {'id' : id},
				success : function(result){
					// alert("통신에 성공");
					
					if(result == 1){
						alert("이미 가입된 아이디입니다.")
					} else {
						alert("가입 가능한 아이디입니다.")
					}
				},
				error : function(request, status, error) {
					// alert("❗ ❗ 문제 발생 ❗ ❗");
				}
			});
		}
		return false;		
	}
		
</script>

</head>
<body>
	<div class="container2">
	<header>
		<%@ include file="menu.jsp"%>
	</header>
		<div class="main">
			<div class="mainStyle">
				<article>
					<div class="join-form"><br>
						<h1>회원가입 회원가입 회원가입 회원가입 회원가입 회원가입 환영합니다 회원가입 회원가입 회원가입 회원가입 환영합니다 회원가입 회원가입 회원가입 회원가입 회원가입 회원가입 환영합니다 회원가입 회원가입 환영합니다 회원가입 회원가입 회원가입 회원가입 환영합니다</h1><br><br>
						<h3>💚 수정중이지만 가입은 가능합니다 💚</h3>
						<div class="mx-3 p-3 rounded-3" style="background-color: #C9ABFC; margin-top: 70px;"	> 
							<form action="./join" method="post" onsubmit="return check()">
								<div class="input-group mb-2">
									<label class="input-group-text"> 아이디 </label>
									<input type="text" id="id" name="id" class="form-control" placeholder="아이디를 입력하세요.">
									<button class="btn btn-success input-group-text" onclick="return idCheck()">ID 중복검사</button>
								</div>
								<div class="input-group mb-2 id-alert">
									<p class="alert">올바른 아이디를 입력하세요.</p>
								</div>
								<div class="input-group mb-2">
									<label class="input-group-text">이 름</label>
									<input type="text" id="name" name="name" class="form-control" placeholder="이름을 입력하세요.">
								</div>
								<div class="input-group mb-2 name-alert">
									<p class="alert">올바른 이름을 입력하세요.</p>
								</div>
								<div class="input-group mb-2">
									<label class="input-group-text">암 호</label>
									<input type="password" id="pw1" name="pw1"  class="form-control" placeholder="암호를 설정해주세요.">
									<label class="input-group-text">재입력</label>
									<input type="password" id="pw2" name="pw2"  class="form-control" placeholder="암호가 맞는지 다시 확인합니다.">
								</div>
								<div class="input-group mb-2 pw-alert">
									<p class="alert">올바른 암호를 입력하세요.</p>
								</div>
								<div class="d-grid gap-2 d-md-flex justify-content-md-end">
									<button type="reset" class="btn btn-primary me-md-2" style="background-color: #8E44EC; border-color: #8E44EC;">초기화</button>
									<button type="submit" class="btn btn-primary" style="background-color: #8E44EC; border-color: #8E44EC;">가입하기</button>
								</div>
							</form>
						</div>
					</div>
					
				</article>
			</div>
		</div>
		<footer>
		<c:import url="footer.jsp"/>
		</footer>
	</div>
	

</body>
</html>

 

 

 

join.java

 

 

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

import com.coffee.dao.MemberDAO;
import com.coffee.dto.BoardDTO;
import com.coffee.dto.MemberDTO;
import com.coffee.util.Util;

@WebServlet("/join")
public class Join extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Join() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher("join.jsp");
		rd.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		MemberDTO dto = new MemberDTO();
		
		// 값 잡기 id name pw
		dto.setMid(request.getParameter("id"));      
	    dto.setMname(request.getParameter("name"));      
	    dto.setMpw(request.getParameter("pw1"));    
        
        // db에 보내기
        MemberDAO dao = new MemberDAO();
        
        // MemberDAO를 사용하여 회원 정보를 데이터베이스에 저장하고 결과를 받아옴
        int result = dao.join(dto);
        
        // 정상적으로 데이터입력을 완료했다면 로그인 페이지로, 비정상이면 에러 페이지로 전송
		if(result == 1) {
			response.sendRedirect("./login");
		} else {
			response.sendRedirect("./error");
		}
	}
}

 

 

idCheck

 


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;

import com.coffee.dao.MemberDAO;
import com.coffee.dto.MemberDTO;

@WebServlet("/idCheck")
public class IDCheck extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public IDCheck() {
        super();
    }

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		String id = request.getParameter("id");
		
		MemberDTO dto = new MemberDTO();
		dto.setMid(id);
		
		MemberDAO dao = new MemberDAO();
		int result = dao.idCheck(dto);

//		System.out.println("검사 요청이 들어온 ID : " + id + " / 결과는 : " + result);
		PrintWriter pw = response.getWriter();
		pw.print(result);
	}

}

 

 

MemberDAO

 

	public int join(MemberDTO dto) {
		int result = 0;
		
		Connection con = db.getConnection();
		PreparedStatement pstmt = null;
		String sql ="INSERT INTO member(mid, mname, mpw) VALUES (?, ?, ?)"; 
	
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getMid());
			pstmt.setString(2, dto.getMname());
			pstmt.setString(3, dto.getMpw());
			
			result = pstmt.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
		return result;
	}



	public int idCheck(MemberDTO dto) {
		int result = 1;
		
		Connection con = db.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="SELECT COUNT(*) FROM member WHERE mid=?"; // select는 rs가 필요함
		
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getMid()); // id는 dto에 있음
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				result = rs.getInt(1);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(rs, pstmt, con);
		}
		return result;
	}

 

반응형

댓글