국비 56 - 비밀번호 변경

냐아암·2023년 8월 7일
0

국비

목록 보기
72/114

비밀번호 변경


<li><a href="${contextPath}/member/myPage/changePw">비밀번호 변경</a></li>
@WebServlet("/member/myPage/changePw")
public class MyPageChangePwServlet extends HttpServlet {
	
	
	// GET 방식 : 비밀번호 변경 페이지
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String path = "/WEB-INF/views/member/myPage-changePw.jsp";
		req.getRequestDispatcher(path).forward(req, resp);
		
	}

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!-- 문자열 관련 함수(메소드) 제공 JSTL (EL 형식으로 작성) -->
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My page</title>

<link rel="stylesheet" href="${contextPath}/resources/css/main-style.css">
<link rel="stylesheet" href="${contextPath}/resources/css/myPage-style.css">

<script src="https://kit.fontawesome.com/8f020b2fa9.js"
   crossorigin="anonymous"></script>
</head>
<body>

   <main>
     <jsp:include page="/WEB-INF/views/common/header.jsp"></jsp:include>
      <!-- 마이페이지 - 내 정보 -->
      <section class="myPage-content">

		<!-- 사이드메뉴 include -->
        <jsp:include page="/WEB-INF/views/member/sideMenu.jsp"></jsp:include>
        
        <!-- 오른쪽 마이페이지 주요 내용 -->
        <section class="myPage-main">
            <h1 class="myPage-title">비밀번호 변경</h1>
            <span class="myPage-explanation">현재 비밀번호가 일치하는 경우 새 비밀번호로 변경할 수 있습니다.</span>

            <form action="changePw" method="POST" name="myPage-form" onsubmit="return changePwValidate()">

                <div class="myPage-row">
                    <label>현재 비밀번호</label>
                    <input type="password" name="currentPw" id="currentPw" maxlength="30">
                </div>
                
                <div class="myPage-row">
                    <label>새 비밀번호</label>
                    <input type="password" name="newPw" maxlength="30">
                </div>
                
                <div class="myPage-row">
                    <label>새 비밀번호 확인</label>
                    <input type="password" name="newPwConfirm" maxlength="30">
                </div>
                
                <button id="info-update-btn">수정하기</button>
            </form>
        </section>

      </section>  

   </main>

   <jsp:include page="/WEB-INF/views/common/footer.jsp"></jsp:include>

   <script src="${contextPath}/resources/js/member/myPage.js"></script>

</body>
</html>

실제 변경 버튼

@WebServlet("/member/myPage/changePw")
// POST방식 요청 : 비밀번호 변경
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// 파라미터(현재 비밀번호, 새 비밀번호) 얻어오기
		String currentPw=req.getParameter("currentPw");
		String newPw=req.getParameter("newPw");
		
		
		// ** 로그인 회원 번호 얻어오기
		HttpSession session = req.getSession(); // 세션 얻어오기
		
		// 로그인 정보 얻어오기
		Member loginMember = (Member)(session.getAttribute("loginMember"));
		
		int memberNo=loginMember.getMemberNo(); // 로그인한 MemberNo
		
		System.out.println(currentPw);
		System.out.println(newPw);
		System.out.println(memberNo);
		
		// ** Service로 전달할 값이 많은데 VO로 해결할 수 없는 경우
		// 1. 매개변수로 하나하나 따로 전달
		// -> 최대 4개를 넘지 않는 것을 권장
		// 2. VO 새로 만들기 (일회성 사용은 비효율적)
		
		
		try {
			
			MemberService service = new MemberService();
			
			int result = service.changePw(currentPw, newPw, memberNo);
			
			String path = null;
			if(result > 0) {
				
				// session scope -> key="message", value="비밀번호 변경 성공"
				session.setAttribute("message", "비밀번호 변경 성공");
				 
				path=req.getContextPath()+"/member/myPage/info"; // 절대경로
				// path="info"; // 상대경로
				
				
			}  else {
				session.setAttribute("message", "현재 비밀번호가 일치하지 않습니다.");
				
				path=req.getContextPath() + "/member/myPage/changePw"; // 절대경로
				// path="changePw"; // 상대경로
			}
			
			resp.sendRedirect(path);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

/** 비밀번호 변경 service
	 * @param currentPw
	 * @param newPw
	 * @param memberNo
	 * @return result
	 * @throws Exception
	 */
	public int changePw(String currentPw, String newPw, int memberNo) throws Exception {
		
		Connection conn = getConnection();
		
		int result = dao.changePw(conn, currentPw, newPw, memberNo);
		
		if(result>0) commit(conn);
		else		 rollback(conn);
		
		close(conn);
		
		
		return result;
	}

/** 비밀번호 변경 DAO
	 * @param conn
	 * @param currentPw
	 * @param newPw
	 * @param memberNo
	 * @return result
	 * @throws Exception
	 */
	public int changePw(Connection conn, String currentPw, String newPw, int memberNo) throws Exception {
		
		int result = 0;
		
		try {
			
			String sql = prop.getProperty("changePw");
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, newPw);
			pstmt.setInt(2, memberNo);
			pstmt.setString(3, currentPw);
			
			result = pstmt.executeUpdate();
			
		} finally {
			
			// try - finally : try구문에서 JDBC 관련 예외가 발생하더라도 
			//				   사용 중이던 JDBC 객체 자원을 무조건 반환하기 위해서
			
			close(pstmt);
		}
		
		return result;
	}

<!-- 비밀번호 변경 -->
	<entry key="changePw">
		UPDATE MEMBER SET
		MEMBER_PW = ?
		WHERE MEMBER_NO=?
		AND MEMBER_PW=?
	</entry>
profile
개발 일지

0개의 댓글