커뮤니티 - 회원 탈퇴 기능 구현 (23.07.11)

·2023년 7월 11일
0

Server

목록 보기
14/35
post-thumbnail

📝 회원 탈퇴 기능


💡 VS Code

🔎 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>

        <!-- /community/member/myPage/secession -->
        <li> <a href="${contextPath}/member/myPage/secession">회원 탈퇴</a> </li>
    </ul>

</section>

🔎 myPage-secession.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/secession (GET)
                     http://localhost:8080/community/member/myPage/secession (POST) -->

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

                    <div class="myPage-row">
                        <label>비밀번호</label>
                        <input type="password" name="memberPw" maxlength="30">
                    </div>

                    <div class="myPage-row info-title">
                        <label>회원 탈퇴 약관</label>
                    </div>

                    <pre id="secession-terms">
제1조
이 약관은 샘플 약관입니다.

① 약관 내용 1

② 약관 내용 2

③ 약관 내용 3

④ 약관 내용 4


제2조
이 약관은 샘플 약관입니다.

① 약관 내용 1

② 약관 내용 2

③ 약관 내용 3

④ 약관 내용 4
                    </pre>

                    <div>
                        <input type="checkbox" name="agree" id="agree">
                        <label for="agree">위 약관에 동의합니다.</label>
                    </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

.
.
.
/* 회원 탈퇴 약관 */
#secession-terms{
    width: 500px;
    height: 300px;
    border: 1px solid black;
    font-size: 16px;

    /* 내용이 지정한 사이즈를 초과한 경우에 대한 속성 */
    overflow: auto; /* 초과한 방향의 스크롤을 자동 생성 */
}

💡 Eclipse

🔎 MyPageSecessionServlet.java

package edu.kh.community.member.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
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/secession")
public class MyPageSecessionServlet extends HttpServlet {

	// 회원 탈퇴 페이지로 전환
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String path = "/WEB-INF/views/member/myPage-secession.jsp";
		
		req.getRequestDispatcher(path).forward(req, resp);
		
	}
	
	// 회원 탈퇴
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// 파라미터
		String memberPw = req.getParameter("memberPw");
		
		// 회원 번호
		HttpSession session = req.getSession(); // 세션 얻어오기
		
		Member loginMember = (Member)( session.getAttribute("loginMember") );
		
		int memberNo = loginMember.getMemberNo();
		
		try {
			MemberService service = new MemberService();
			
			int result = service.secession(memberNo, memberPw);
			
			String path = null; // 리다이렉트 경로
			
			if(result > 0) { // 성공
				// 로그아웃 방법 1
				// path = req.getContextPath() + "/member/logout"; // 로그아웃 요청으로 리다이렉트
				
				// 로그아웃 방법 2
				session.invalidate(); // 세션 무효화
				// -> 세션을 무효화해 버려서 메시지 전달이 되지 않는 문제가 발생
				
				// [해결 방법]
				// 새로운 세션을 얻어와서 메시지 세팅
				
				session = req.getSession(); // 무효화 후 새로 생성된 세션 얻어오기
				
				session.setAttribute("message", "탈퇴되었습니다.");
				
				path = req.getContextPath(); // 메인 페이지
				
				Cookie c = new Cookie("saveId", ""); // 쿠키 생성
				c.setMaxAge(0); // 쿠키 수명
				c.setPath(req.getContextPath()); // 쿠키 적용 경로
				resp.addCookie(c); // 쿠키 클라이언트에 전송
				
			} else { // 실패
				session.setAttribute("message", "비밀번호가 일치하지 않습니다.");
				
				// 절대 경로
				// path = req.getContextPath() + "/member/myPage/secession";
				
				// 상대 경로
				path = "secession";
			}
			
			resp.sendRedirect(path);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

🔎 MemberService.java

	/** 회원 탈퇴 Service
	 * @param memberNo
	 * @param memberPw
	 * @return result
	 * @throws Exception
	 */
	public int secession(int memberNo, String memberPw) throws Exception {
		
		Connection conn = getConnection();
		
		int result = dao.secession(conn, memberNo, memberPw);
		
		if(result > 0) commit(conn);
		else		   rollback(conn);
		
		close(conn);
		
		return result;
	}

🔎 MemberDAO.java

	/** 회원 탈퇴 DAO
	 * @param conn
	 * @param memberNo
	 * @param memberPw
	 * @return result
	 * @throws Exception
	 */
	public int secession(Connection conn, int memberNo, String memberPw) throws Exception{
		
		int result = 0;
		
		try {
			
			String sql = prop.getProperty("secession");
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, memberNo);
			pstmt.setString(2, memberPw);
			
			result = pstmt.executeUpdate();
			
		} finally {
			close(pstmt);
		}

		return result;
	}

profile
풀스택 개발자 기록집 📁

0개의 댓글