본문 바로가기
오답노트

게시판에서 비밀번호 변경해보기

by titlejjk 2023. 6. 7.

학원에서 수업하다가 잠깐 내주신 과제인데 못풀어서 안까먹으려고 다시 적는다.

로그인 후에 마이페이지에서 비밀번호를 변경하는 jsp를 만드는 과제인데 손놓고 아무것도 못했다. 화딱지 나서 복습겸 다시 적어 보겠다.

머릿속 기본구상은 이러했다.

로그인->마이페이지->비밀번호 변경 버튼 클릭->기존 비밀번호 입력-> 새로 사용할 비밀번호 입력과 새로 사용할 비밀번호를 재입력하여 확인 과정 거치기 -> 완료되면 완료되었다는 이벤트와 함께 info.jsp로 이동

먼저 pwd_update.jsp/pwd_updateform.jsp라는 이름의 jsp파일을 만들어 주었다.

그 안에 코드 작성부분을 쭉 적어보겠다.

먼저 기존 비밀번호와 새 비밀번호를 입력할 pwd_updateform.jsp form을 작성해 주겠다.

<%@page import="test.users.dto.UsersDto"%>
<%@page import="test.users.dao.UsersDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/users/private/pwd_updateform.jsp</title>
</head>
<body>
	<div class = "container">
		<h1>비밀 번호 수정 페이지</h1>
		<form action="pwd_update.jsp" method = "post" id = "myForm">
			<div>
				<label for="pwd">기본 비밀전호</label>
				<input type="password" name = "pwd" id = "pwd"/>
			</div>
			<div>
				<label for="newPwd">새 비밀번호</label>
				<input type="password" name = "newPwd" id = "newPwd"/>
			</div>
			<div>
				<label for="newPwd2">새 비밀번호 확인</label>
				<input type="password" id = "newPwd2"/>
			</div>
			<button type = "submit">수정하기</button>
			<button type = "reset">다시수정</button>
		</form>
	</div>
	<script>
		//폼에 submit 이벤트가 일어났을 때 실행할 함수를 등록하고
		document.querySelector("#myForm").addEventListener("submit", (e)=>{
			//입력한 새 비밀번호 2개를 읽어와서
			let pwd1 = document.querySelector("#newPwd").value;
			let pwd2 = document.querySelector("#newPwd2").value;
			//만일 새 비밀번호와 비밀번호 확인이 일치하지 않으면 폼 전송을 막는다.
			if(pwd1 != pwd2){
				alert("비밀번호를 확인 하세요!");
				e.preventDefault();
			}
		});
	</script>
</body>
</html>

코드 아래 script부분을 작성하시길래 script도 쓰이나 했는데 위 script부분 코드를 해석해보겠다.

버튼을 눌렀을 때 새로 쓸 두개의 비밀번호가 서로 일치하지 않으면 폼에 전송이 되지 않도록 하는 코드이다.

1. 이벤트리스너를 등록을 해서 "submit"이 type으로 걸려있는 버튼을 눌렀을 경우에  myForm에 적용되도록하는 코드이다.

document.querySelector("#myForm").addEventListener("submit", (e){});

2. 입력한 새 비밀번호 2개를 script에 가져온다

let pwd1 = document.querySelector("#newPwd").value;
let pwd2 = document.querySelector("#newPwd2").value;

3. 2번에 비밀번호 두개가 맞는지 확인하는 if문을 만들고 맞지 않을 경우 경고창과 폼으로의 전송을 막는다.

if(pwd1 != pwd2){
	alert("비밀번호를 확인하세요!"); //맞지않을 경우 경고창 출력
    e.preventDefault(); //맞지 않을 경우 폼전송을 막는 메소드
}

그 다음으로 pwd_update.jsp로 넘어간다.

<%@page import="test.users.dto.UsersDto"%>
<%@page import="test.users.dao.UsersDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   //session scope 에서 수정할 회원의 아이디를 읽어온다.
   String id=(String)session.getAttribute("id");
   //폼 전송되는 구 비밀번호, 새 비밀번호 읽어오기
   String pwd=request.getParameter("pwd");
   String newPwd=request.getParameter("newPwd");   
   
   //작업의 성공여부
   boolean isSuccess=false;
   //현재 비밀번호 
   String currentPwd=UsersDao.getInstance().getData(id).getPwd();
   //만일 현재 비밀번호하고 입력한 비밀번호와 같으면 
   if(currentPwd.equals(pwd)){
      //수정 작업을 수행
      UsersDto dto=new UsersDto();
      dto.setId(id);
      dto.setPwd(newPwd);
      isSuccess = UsersDao.getInstance().updatePwd(dto);
   }
   
   //만일 성공이면
   if(isSuccess){
      //로그아웃 처리
      session.removeAttribute("id");
   }
   //응답하기
%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/users/private/pwd_update.jsp</title>
</head>
<body>
<div class="container">
   <%if(isSuccess){ %>
      <p>
         비밀 번호를 수정하고 로그 아웃되었습니다.
         <a href="${pageContext.request.contextPath }/users/loginform.jsp">다시 로그인</a>
      </p>
   <%}else{ %>
      <p>
         구 비밀번호가 일치하지 않습니다.
         <a href="${pageContext.request.contextPath }/users/private/pwd_updateform.jsp">다시 시도</a>
      </p>
   <%} %>
</div>
</body>
</html>

session scope에서 수정할 회원의 아이디를 읽어온다.

String id = (String)session.getAttribute("id");

폼에서 전송되는 기존 비밀번호와, 새 비밀번호를 읽어온다.

String pwd = request.getParameter("pwd"); //기존 비밀번호
String newPwd = request.getParameter("newPwd"); //새로 사용할 비밀번호

DB에서 현재 비밀번호를 가져온다.

String currentPwd = UsersDao.getInstance().getData(id).getPwd();
//UsersDao에 getInstance()를 거쳐 getData()에 id를 넣어주고 .getPwd()로 비밀번호를 가져온다.
//이 코드가 필요한 이유는 DB에 있는 비밀번호를 가져와서 위에 입력한 비밀번호와 대조하기 위해 작성

현재 비밀번호와 입력한 비밀번호가 같으면 비밀번호를 수정하는 작업을 실행해준다. 수정하기전에 수정할 sql문을 UsersDao에 만들어준다.

//비밀번호를 수정하는 메소드
	public boolean updatePwd(UsersDto dto) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int rowCount = 0;
		try {
			//DbcpBean 객체를 이용해서 Connection 객체를 얻어온다(Connection Pool 에서 얻어오기)
			conn = new DbcpBean().getConn();
			//실행할 sql 문 
			String sql = "UPDATE users"
					+ " SET pwd = ?"
					+ " WHERE id = ?";
			pstmt = conn.prepareStatement(sql);
			//sql 문이 미완성이라면 여기서 완성
			pstmt.setString(1, dto.getPwd());
			pstmt.setString(2, dto.getId());
			//select 문 수행하고 결과값 받아오기
			rowCount = pstmt.executeUpdate();
			//반복문 돌면서 ResultSet 에 담긴 내용 추출
		} catch (SQLException se) {
			se.printStackTrace();
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
			}
		}
		//만일 변화된 row 의 갯수가 0 보다 크면 작업 성공
		if (rowCount > 0) {
			return true;
		} else {
			return false;
		}

	}

UsersDao에 비밀번호를 수정할 메소드를 다 만들었으면 if문을 통해 현재비밀번호와 입력한 비밀번호를 대조하고 true면 if문을 실행할 코드를 작성해준다.

if(currentPwd.equals(pwd){
	UsersDto dto = new UsersDto(); //새로운 dto객체를 만들어주고(id랑 새로운비밀번호를 담을)
    //session영역에 있는 id를 넣어주는 것
    dto.setId(id); 
    //pwd_updateform에서 넣어준 새로운 비밀번호
    dto.setPwd(newPwd); 
    //위 dto에 넣어준 값을 UsersDao에 있는 updatePwd메소드에 인자값을 전달해 isSuccess를 true로 변환해준다.
    //isSuccess는 전역변수 boolean type으로 false;값을 초기값으로 해서 선언해준다.
    isSuccess = UsersDao.getInstance().updatePwd(dto); 
}

위 if문이 성공이면 로그아웃처리를 하는 다른 if문을 만들어준다.

if(isSuccess){ //위에 if문이 true인 값인 상태로 넘어오게 되면
	//로그아웃처리 session scope에 있는 id값을 .removeAttribute("id")를 통해 삭제하여 로그아웃처리
    session.removeAttribute("id");
}

응답하는 영역을 만든다. 응답하는 부분은 비밀번호가 수정이 완료되었는지 아니면 이전에 사용하던 비밀번호가 일치하지 않는지 확인해 본다.

이 영역은 html부분에 적어주었다.

<body>
	<div class = "container">
    	<%if(isSuccess){ %>
        	<p>
            	비밀 번호를 수정하고 로그아웃되었습니다.
                <a href = "${pageContext.request.contextPath }/users/loginform.jsp">다시 로그인</a>
            </p>
        <%}else{ %>
        	<p>
            	구 비밀번호가 일치하지 않습니다.
                <a href="${pageContext.request.contextPath }/users/private/pwd_updateform.jsp">다시 시도</a>
            </p>
        <%} %>
    </div>
</body>

 

댓글