프로그래밍/Java_JSP 게시판 만들기

Java_JSP 게시판 만들기 가입하기(ajax방식)

개발계발게발 2021. 7. 13. 17:23
반응형

ajax 방식 중복 ID 체크

 

join.jsp

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
$(function(){
	//html이 로딩 되고 바로 가입버튼 비활성화 하기
	$("#join_join").prop("disabled", true);	
});
function checkID(){
	//var id = $(선택자).명령();
	var id = $("#id").val();
	//alert(id);
	if(id == "" || id.length < 4){
		alert("아이디를 입력해주세요.");
		$("#id").focus();
		return false;
	}
	$.ajax({
		type:'post',
		dataType:'text',
		data: 'id='+id,
		url: './idCheck',
		success: function(rData, textStatus, xhr){
			var checkResult = rData;
			//alert("성공 : " + checkResult);
			if(checkResult == 1){
				alert(id + "는 이미 등록되어 있습니다.");
				$("#join_join").prop("disabled", true); //비활성화
				$("#resultText").css("color", "red");
				$("#resultText").text(id + "는 이미 등록되어 있습니다.");
				return false;
			}else{
				alert(id + "는 가입 할 수 있습니다.");
				$("#join_join").prop("disabled", false); //활성화
				$("#resultText").css("color", "blue");
				$("#resultText").text(id + "는 가입 가능합니다.");
			}
		},
		error: function(xhr, status, e){
			alert("문제 발생 : " + e);
		}
	});
}

 

IdCheck.java (servlet)

package com.knowhoon.web;

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.knowhoon.dao.LoginDAO;

@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 {
		System.out.println("POST 요청");
		String id = request.getParameter("id");
		int result = 1; // 있다 = 1
		System.out.println(id);
		//response.getWriter().write(1);
		LoginDAO dao = new LoginDAO();
		result = dao.idCheck(id);
		
		PrintWriter pw = response.getWriter();
		pw.print(result);
		
	}

}

 

LoginDAO - idCheck()함수

public int idCheck(String id) {
		Connection conn = DBConnection.dbConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int result = 0;
		String sql = "SELECT COUNT(*) FROM login WHERE id=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				result = rs.getInt("COUNT(*)");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null) {pstmt.close();}
				if (conn != null) {conn.close();}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("id는" + result);
		return result;
	}

 

반응형