커뮤니티 - 비밀번호 수정 기능 구현 (23.07.11)

·2023년 7월 11일
0

Server

목록 보기
13/35
post-thumbnail

📝 비밀번호 수정 기능


💡 Eclipse

🔎 sideMenu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- 왼쪽 사이드 메뉴 -->
<section class="left-side">
    사이드 메뉴

    <ul class="list-group">
        <li> <a href="#">프로필</a> </li>
        
        <!-- /community/member/myPage/info -->
        <li> <a href="${contextPath}/member/myPage/info">내 정보</a> </li>
        
        <!-- /community/member/myPage/changePw -->
        <li> <a href="${contextPath}/member/myPage/changePw">비밀번호 변경</a> </li>
        <li> <a href="#">회원 탈퇴</a> </li>
    </ul>

</section>

🔎 myPage-info.jsp

.
.
.
<body>

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

			<!-- 사이드메뉴 include  -->
			<jsp:include page="/WEB-INF/views/member/sideMenu.jsp"/>
.
.
.

🔎 MyPageChangePwServlet.java

package edu.kh.community.member.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

import edu.kh.community.member.model.service.MemberService;
import edu.kh.community.member.model.vo.Member;

@WebServlet("/member/myPage/changePw")
public class MyPageChangePwServlet extends HttpServlet{

	// get방식 요청 : /WEB-INF/views/member/myPage-changePw.jsp 요청 위임
	@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);
	}
	
	// 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(); // 로그인 회원 번호
		
		System.out.println(currentPw);
		System.out.println(newPw);
		System.out.println(memberNo);

		// ** Service로 전달할 값이 많은데 VO로 해결할 수 없는 경우 **
		// 1. 매개변수로 하나하나 따로 전달한다.
		//    -> 최대 4개를 넘지 않는 것을 권장
		
		// 2. VO 새로 만들기(1회성으로 사용하면 비효율적)
		
		try {
			
			MemberService service = new MemberService();
			
			int result = service.changePw(currentPw, newPw, memberNo);
			
			String path = null; // 리다이렉트 주소
			
			if(result > 0) { // 성공
				// session scope -> key="message", value="비밀번호 성공!"
				// path = "내 정보 페이지 주소"
				session.setAttribute("message", "비밀번호 성공!");
				
				// path = req.getContextPath() + "/member/myPage/info";
				path = "info";
				
			} else { // 실패
				// session scope -> key="message", value="현재 비밀번호가 일치하지 않습니다"
				// path = "비밀번호 변경 페이지 주소"
				session.setAttribute("message", "현재 비밀번호가 일치하지 않습니다.");
				
				// path= req.getContextPath() + "/member/myPage/changePw";
				path = "changePw";
			}
			
			resp.sendRedirect(path);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

🔎 myPage-changePw.jsp

<%@ 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/4dca1921b4.js" crossorigin="anonymous"></script>

</head>
<body>

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

			<!-- 사이드메뉴 include  -->
			<jsp:include page="/WEB-INF/views/member/sideMenu.jsp"/>

            <!-- 오른쪽 마이페이지 주요 내용 부분 -->
            <section class="myPage-main">

                <h1 class="myPage-title">비밀번호 변경</h1>
                <span class="myPage-explanation">현재 비밀번호가 일치하는 경우 새 비밀번호로 변경할 수 있습니다.</span>

                <!-- http://localhost:8080/community/member/myPage/changePw (GET)
                     http://localhost:8080/community/member/myPage/changePw (POST) -->

                <form action="changePw" method="POST" name="myPage-form">

                    <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"/>

</body>
</html>

🔎 myPage-style.css

/* 마이페이지 영역 */
.myPage-content{
    width: 1000px;
    height: 800px;
    margin: 50px auto;

    display: flex;
}

/* 왼쪽 사이드 메뉴 */
.left-side{
    width: 25%;
    border-right: 2px solid #ddd;
}

.list-group{
    width: 100%;
    padding: 0 20px 0 0;
          /* 상 우 하 좌 */
}

.list-group > li{
    list-style: none;
    height: 50px;
    font-size: 18px;
}

.list-group > li > a{
    text-decoration: none;
    color: black;
    height: 100%;

    border-bottom: 2px solid #ddd;

    display: flex;

    justify-content: center;
    align-items: center;
}

.list-group > li:hover{
    background-color: #f2f2f2;
}

/* 마이페이지 공통 부분 */
.myPage-main{
    width: 75%;
    padding: 0 50px;
}

.myPage-title{
    margin: 0 0 10px 0;
    font-size: 30px;
}

.myPage-explanation{
    display: block;
    font-size: 14px;
    margin-bottom: 30px;    
    letter-spacing: -1px;
}

.myPage-row{
    width: 500px;
    height: 50px;
    margin-top: 20px;

    display: flex;
    align-items: center;
    border-bottom: 2px solid #ddd;
}

.myPage-row > *{
    font-size: 18px;
    font-weight: bold;
}

.myPage-row > label{
    width: 30%;
    color: #455ba8;
}

.myPage-row > span{
    width: 70%;
}

.myPage-row > input{
    width: 100%;
    height: 100%;
    border: 0;
    outline: 0;
    font-weight: normal;
}

.myPage-row:focus-within{
    border-bottom: 2px solid #455ba8;
}

form[name="myPage-form"]{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 내 정보 */
.info-title{
    color: #455ba8;
    border: 0;
}

.info-address{ margin: 0; }

/* 검색 버튼 */
#info-address-btn{
    width: 30%;
    height: 70%;
    
    font-size: 14px;
    font-weight: normal;

    background-color: white;
    border: 1px solid gray;
    cursor: pointer;
}

#info-update-btn{
    width: 100%;
    padding: 10px;
    margin: 50px 0;
    border: none;
    font-size: 20px;
    font-weight: bold;
    background-color: #455ba8;
    color: white;
    cursor: pointer;
}

/* 비밀번호 변경 */
.myPage-row > input[type="password"]{
    width: 70%;
}

🔎EncryptWrapper.java

.
.
.
	// getParameter() 오버라이딩
	@Override
	public String getParameter(String name) {
		// 매개변수 name : input 태그의 name 속성 값
		// super.getParameter(name) : 기존 getParameter() 메소드
		
		String value = null;
		
		switch(name) {
		case "inputPw" :
		case "memberPw" :
		case "currentPw" :
		case "newPw" :
			value = getSha512( super.getParameter(name) );
			break;
			
		// 암호화 되는 경우가 아니라면 기존 getParameter() 메소드 형태를 유지	
		default : value = super.getParameter(name);
		}
		
		return value;
	}
.
.
.

🔎 MemberService.java

.
.
.
	/** 비밀번호 수정 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;
	}

.
.
.

🔎 MemberDAO.java

.
.
.
	/** 비밀번호 변경 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;
	}
.
.
.

profile
풀스택 개발자 기록집 📁

0개의 댓글