이메일 중복 확인 버튼 클릭 이벤트:
const btnSendEmail = document.getElementById('btnSendEmail');
const emailResult = document.querySelector('.emailResult');
const auth = document.querySelector('.auth');
btnSendEmail.onclick = async function() {
const value = formRegister.email.value;
const response = await fetch('/jboard/user/check.do?type=email&value=' + value);
const data = await response.json();
if (data.count > 0) {
emailResult.innerText = '이미 사용중인 이메일 입니다.';
emailResult.style.color = 'red';
} else {
// 인증번호 입력 필드 출력
auth.style.display = 'block';
}
}
btnSendEmail 버튼 클릭 시 사용자가 입력한 이메일을 가져와 서버에 요청을 보냄data.count)가 0보다 크면 '이미 사용중인 이메일 입니다.'라는 메시지를 빨간색으로 표시이메일 중복 확인 요청 처리:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 데이터 수신
String type = req.getParameter("type");
String value = req.getParameter("value");
// 수신된 데이터 출력
System.out.println("type : " + type + ", value : " + value);
logger.debug("type : " + type + ", value : " + value);
// 카운트 조회
int count = service.countUser(type, value);
logger.debug("count : " + count);
// 이메일 인증번호 발송
if (type.equals("email") && count == 0) {
String code = service.sendEmailCode(value);
// 세션 저장
HttpSession session = req.getSession();
session.setAttribute("sessAuthCode", code);
}
// JSON 생성
JsonObject json = new JsonObject();
json.addProperty("count", count);
logger.debug("json : " + json);
// JSON 출력
PrintWriter writer = resp.getWriter();
writer.println(json);
}
type, value)를 수신public String sendEmailCode(String receiver) {
// 인증번호 생성
int code = ThreadLocalRandom.current().nextInt(100000, 1000000);
// Gmail 기본정보
String sender = "[email protected]";
String title = "jboard 인증코드 입니다.";
String content = "<h1>인증코드는 " + code + "입니다.</h1>";
String appPassword = "qxwh susp mpay neki";
// Gmail SMTP 서버 설정
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.trust", "smtp.gmail.com");
// Gmail SMTP 세션 생성
Session gmailSession = Session.getInstance(prop, new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, appPassword);
}
});
// 메일 발송
Message message = new MimeMessage(gmailSession);
try {
message.setFrom(new InternetAddress(sender, "보내는 사람", "UTF-8"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
message.setSubject(title);
message.setContent(content, "text/html;charset=UTF-8");
Transport.send(message);
} catch(Exception e) {
e.printStackTrace();
}
return "" + code;
}
const btnAuthEmail = document.getElementById('btnAuthEmail');
btnAuthEmail.onclick = async function() {
const value = formRegister.auth.value;
// 폼 데이터 생성
const formData = new URLSearchParams();
formData.append("authCode", value);
// 서버 전송
const response = await fetch('/jboard/user/check.do', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: formData
});
const data = await response.json();
console.log(data);
if (data.result > 0) {
emailResult.innerText = '이메일이 인증 되었습니다.';
emailResult.style.color = 'green';
} else {
emailResult.innerText = '유효한 인증코드가 아닙니다.';
emailResult.style.color = 'red';
}
}