티스토리 뷰

1. join.jsp

아무나 회원가입 할 수 없게 본인인증을 할 수 있는 이메일 인증을 회원가입때 구현해 놓았다.

<div class="box1">
	<div>
		<div class="labelbox"><label>이메일*</label></div>	
		<div class="box2"><input type="text" name="email" id="userEmail1"></div>
		<div class="msgbox">
			<span id="emailMsg" style="font-size: 17px;"></span>	
		</div>	
		<div class="box3">
			<input type="text" name="email_checknumber" id="email_checknumber" placeholder="인증번호를 입력해주세요">
			<input type="button" id="emailbtn" name="emailbtn" value="본인인증">
		</div>
		<div style="padding-top:8px;">
			<span id="emailNumMsg" style="font-size: 17px;"></span>
		</div>
	</div>
</div>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	// 이메일 인증
	var code = ""; // 인증번호 저장을 위한 코드
	var isCertification = false; // 인증 여부 변수
	const checkInput = $('#email_checknumber'); // 인증번호 입력하는 곳

	$('#emailbtn').click(function() {
		const email = $('#userEmail1').val() 
		console.log('완성된 이메일: ' + email); // 이메일 오는지 확인
        
		$.ajax({
			type: 'GET',
			url: '/login/mailCheck?email=' + email,
			dataType: 'text',
			success: function(data) {
				code = data;
				isCertification = true; // 인증이 완료되었음을 표시
				alert('인증번호가 전송되었습니다.');
				$('#submit').attr('disabled', false);
			},
			error : function() { // 결과 에러 콜백함수
				alert('서버요청 실패');
			}      
		}); // end ajax
	}); // end send email

	// 인증번호 비교 
	// blur -> focus가 벗어나는 경우 발생
	$('#email_checknumber').blur(function () {
		const inputCode = $('#email_checknumber').val();
		const resultMsg = $('#emailNumMsg');

		if (!isCertification) {
			resultMsg.html('인증이 완료되지 않았습니다.');
			resultMsg.css('color', 'red');
		} else if (inputCode === code) {
			resultMsg.html('인증번호가 일치합니다.');
			resultMsg.css('color', 'green');
			$('#emailbtn').attr('disabled', true);
			$('#userEamil1').attr('readonly', true);
			$('#userEmail1').attr('onFocus', 'this.initialSelect = this.selectedIndex');
 			$('#userEmail1').attr('onChange', 'this.selectedIndex = this.initialSelect');
 			checkInput.attr('disabled', true); // 인증번호 입력이 가능하도록 속성 변환
		} else if (inputCode === '') {
			resultMsg.html('인증번호를 입력해주세요.');
			resultMsg.css('color', 'red');
		} else {
			resultMsg.html('인증번호가 불일치합니다. 다시 확인해주세요!.');
			resultMsg.css('color', 'red');
		}
	});

	// 인증번호가 다르면 submit 안되게
	$('#submit').click(function() {
		if (!isCertification) {
			alert('인증이 완료되지 않았습니다.');
			return false;
		} else {return true;}
	});
});
</script>

이메일 인증은 ajax로 데이터를 컨트롤러로 전송해주는 방식이었고 처음 클릭할 수 있는 버튼들을 전부 <button>태그들로 해 놓은 상태라 데이터들이 제대로 가지 않는 상황이었다. 이때는 버튼 속성에 onclick을 준다음 함수명을 써주던가 버튼에 클릭 이벤트를 넣어서 클릭하면 어떤 기능을 하게 만들어주는 식으로 지정해주어야 한다. 버튼의 기본 속성은 submit인데 따로 지정해 주지 않으면 form 태그 안에서 지정한 방법인 post로 데이터를 보내주려고 하기 때문.

 

2. jsp에서 ajax를 통해 받아온 데이터를 컨트롤러의 get메소드로 받아낸다,그리고 서비스에서 불러온 emaiilAuth메소드를 리턴해준다. 

@Controller
@ResponseBody
public class MailController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired MailService mailService;

	// 이메일 인증 버튼 클릭
	@GetMapping("/login/mailCheck")
	public String emailCheck(String email) {
		logger.info("email 옵니다~");	
		logger.info("email 주소 : {}",email);

		return mailService.emailAuth(email);
	} // emailCheck() end
} // MailController() end

3. service 1 - 랜덤난수 만들어주기

인증번호를 랜덤으로 생성해 주는 메소드를 구현해준다. 이떄 랜덤으로 발생한 인증번호는 smtp서버에 저장된다. 이 저장된 번호를 스크립트로 비교해주면 이메일 인증을 할수 있게 된다. 

public void makeRandomNumber() {				
    // 인증번호용 랜덤 난수 생성
    Random n = new Random();

    //111111 ~ 999999까지 인증번호 : .nextInt() + n => 범위지정
    int randomNum = n.nextInt(888888)+111111;
    logger.info("인증번호 : {}",randomNum);
    authNumber = randomNum;	

	} // makeRandomNumber() end

4. service 2 - 메일보내기

자바에서 지원하는 maiilSender 클래스를 사용해서 이메일을 보낼 수 있다.

@Override
	public String emailAuth(String email) {
		makeRandomNumber();
		String setFrom = "projectemailauth@gmail.com"; // email-config에 설정한 자신의 이메일 주소를 입력 
		String toMail = email;
		String title = "회원 가입 인증 이메일 입니다."; // 이메일 제목 
		String content = 
				"홈페이지를 방문해주셔서 감사합니다." + 	//html 형식으로 작성 ! 
                "<br><br>" + 
			    "인증 번호는 " + authNumber + "입니다." + 
			    "<br>" + 
			    "해당 인증번호를 인증번호 확인란에 기입하여 주세요."; //이메일 내용 삽입
		mailSend(setFrom, toMail, title, content);
		
		return Integer.toString(authNumber);
	} // emailAuth(String email) end
	
	//이메일 전송 메소드
	public void mailSend(String setFrom, String toMail, String title, String content) { 
		MimeMessage message = mailSender.createMimeMessage();
		// true 매개값을 전달하면 multipart 형식의 메세지 전달이 가능.문자 인코딩 설정도 가능하다.
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8");
			helper.setFrom(setFrom);
			helper.setTo(toMail);
			helper.setSubject(title);
			// true 전달 > html 형식으로 전송 , 작성하지 않으면 단순 텍스트로 전달.
			helper.setText(content,true);
			mailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

자바 mailsender클래스는 추가해야함.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함