[Servlet&JSP] Chap 7. 회원 정보 수정, 비밀번호 수정(MVC2 패턴)

김승현·2021년 12월 14일
0
post-custom-banner

회원 정보 수정

  1. index.jsp

    • 이름 또는 마이페이지 클릭 -> MemberCheckServlet.java(/member/memberCheck.do)으로 가지(URL 보안때문에)
  2. MemberCheckServlet.java(/member/memberCheck.do)

    • 세션이 있는 지 확인(간단한 확인)
      1) 있다면 -> myPagePasswordCheck.jsp(비밀번호 재 확인 창이동) (URL 노출 X)
      2) 없다면 ->/views/commons/error.jsp 파일로 이동(URL 노출 X) -> 오류메시지, 메인페이지로 이동 링크
  3. myPagePasswordCheck.jsp -> URL노출 X

    • 비밀번호 확인 폼 작성 후 submit->MyPageServlet.java(/member/myPage.do)
  4. MyPageServlet.java(/member/myPage.do)

    • 비밀 번호 확인 비즈스 로직 with userId(<->Service<->DAO)
    • 리턴 값 처리
      1) Member 객체
      - session 갱신
      - 회원 정보 나오는 페이지로 이동(myPage.jsp) (URL노출 X)
      2) null
      - 실패 페이지(myPagePasswordCheckFail.jsp)로 이동(URL노출 X) -> alert 띄어주고 2번으로
  5. myPage.jsp

    • 회원 정보 및 수정할수 있는 폼
    • 수정 후 servlet으로 요청 전달 -> MemberUpdateServlet(/member/memberUpdate.do)
  6. MemberUpdateServlet(/member/memberUpdate.do)

    • 인코딩(for 한글)
    • 이전 페이지에서 값 넘겨받아( with 유니크 정보 userId) 비즈니스 로직 (<->Service<->DAO)
    • 결과값 처리, request에 값담아 -> memberUpdateResult.jsp 이동 (URL노출 X)
      1 ) result>0
      - true
      2) 아니면
      - false
  7. memberUpdateResult.jsp (URL노출 X)

    • 넘겨 받은 값에 따라 alert주고
    • MemberCheckServlet.java(/member/memberCheck.do) 이동



비밀번호 변경

  1. MemberCheckServlet.java(/member/memberCheck.do) ->myPagePasswordCheck.jsp

    • 비밀 번호 수정 버튼 클릭(JS) -> 팝업창열기(memberPasswordChangeWindow.jsp)
  2. memberPasswordChangeWindow.jsp

    • 현재PW, 새PW, 새PW 확인 후 submit
    • MemberPwdChangeServlet.java(/member/memberPwdChange.do)로 이동
  3. MemberPwdChangeServlet.java(/member/memberPwdChange.do)

    • 현재PW, 새PW, 새PW 받아오기 with userId(기준이될 유니크한 정보) 비즈니스 로직
      (<->Service<->DAO)
    • 리턴값의 결과에 따라 request에 true, false 담아서 memberPwdChResult.jsp로 보내기(RequestDispatcher 이용)
  1. memberPwdChResult.jsp -> URL 노출 X
    • request 받아와서 결과 값에 따라 alert 띄어주기
      1) true : 팝업창 닫고 alert
      2) false: alert 후 새 팝업창 열기(memberPasswordChangeWindow.jsp)



index.jsp

<%@page import="kr.or.iei.member.model.vo.Member"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
	#loginForm{
		border : 1px solid grey;
		width : 300px;
		height : 250px;
		margin: 0 auto;
	}
	*{
	box-sizing: border-box;
	
	}
</style>
</head>
<body>
<H3>메인 페이지 (기본)</H3>

<%
	Member m = (Member)session.getAttribute("member");
%>

<%if(m!=null){ %>
	[<a href="/member/memberCheck.do"><%=m.getUserName()%></a>] 님 환영합니다!! <a href="/member/logout.do">로그아웃</a><br>
	
	
	<a href="/member/memberCheck.do">마이 페이지</a><br>
	<a href="/views/file/fileUploadPage.jsp">파일 업로드 페이지</a><br>
	<a href="/file/fileList.do">파일 목록 페이지</a><br>

	
	<%if(m.getRoll().substring(0, 2).equals("AD")){	//관리자로 구분되어진 사용자라면 %>

		<a href="/admin/memberAllList.do">회원관리 페이지</a><br>
		<a href="/admin/boardAllList.do">게시판 관리 페이지</a><br><br><hr>
	
	<%}else{ %>
		<a href="/member/memberWithDraw.do" id="withDraw">회원 탈퇴</a><br><br><hr>
	<%} %>
	
	<script>
		document.getElementById('withDraw').onclick=function(){
			
			
			// 1. 탈퇴를 진행하시겠습니까?
			// 2. 탈퇴를 하시게 되면, 데이터는 절대 복구 불가능합니다.
			
			if(window.confirm("탈퇴를 진행하시겠습니까?") && window.confirm("탈퇴를 하시게 되면, 데이터는 절대 복구 불가능합니다."))
			{
				return true;
			}else
			{
				return false;
			}

			
			
		};
	
	</script>
	
	
	
<%}else{ %>
<div id="loginForm">
	<form action="/member/login.do" method="post">
		<fieldset>
		<legend style="text-align: center;">로그인</legend>
		<input type="text"  class="b-block w-100" name="userId" placeholder="ID를 입력하세요"/><br><br>
		<input type="password" class="b-block w-100"  name="userPwd" placeholder="PW를 입력하세요"/><br><br>
		<input type="submit" class="btn btn-primary b-block w-100" value="로그인"/>
		</fieldset>
		<br>
		<a href="/views/member/memberJoinus.jsp" style="display:block; text-align: right;">회원가입</a>
	</form>
</div>

<%} %>

<a href="/board/boardAllSelectNP.do">게시판(페이징 처리 X)</a><br>
<a href="/board/boardAllSelect.do">게시판(페이징 처리 O)</a><br>
 
</body>
</html>



MemberCheckServlet.java

package kr.or.iei.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;

/**
 * Servlet implementation class MemberCheckServlet
 */
@WebServlet("/member/memberCheck.do")
public class MemberCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MemberCheckServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 간단하게 회원 로그인 한 사용자인지 검증하고, 문제 없으면 비밀번호를 입력하는 페이지로 이동
		HttpSession session= request.getSession();

		RequestDispatcher view;
		
		if(session.getAttribute("member")!=null) {	// 회원 정보를 꺼냈을때 있다면 -> 로그인한 사용자라면
			view = request.getRequestDispatcher("/views/member/myPagePasswordCheck.jsp");
		}else {	// 회원 정보를 꺼냈을때 없다면-> 비로그인한 사용자라면
			view = request.getRequestDispatcher("/views/commons/error.jsp");
		}
		
		view.forward(request, response);
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



myPagePasswordCheck.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
	#passwordForm{
		border : 1px solid grey;
		width : 300px;
		height : 200px;
		margin: 200px auto;
	}
	*{
		box-sizing: border-box;
	
	}
</style>

</head>
<body>

	<div id="passwordForm">
		
		<form action="/member/myPage.do" method="post">
			<fieldset>
			<legend style="text-align: center;">비밀번호 확인</legend>
			
			<input type="password" class="b-block w-100"  name="userPwd" placeholder="PW를 입력하세요"/><br><br>
			<input type="submit" class="btn btn-primary b-block w-100" value="개인정보 수정"/><br><br>
			</fieldset>
		</form>
		<a href="/" style="display:block; text-align:center;" class="btn btn-primary b-block w-100">메인페이지로 이동</a>
	</div>



</body>
</html>



MyPageServlet.java

package kr.or.iei.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 kr.or.iei.member.model.service.MemberService;
import kr.or.iei.member.model.service.MemberServiceImpl;
import kr.or.iei.member.model.vo.Member;

/**
 * Servlet implementation class MyPageServlet
 */
@WebServlet("/member/myPage.do")
public class MyPageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyPageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 사용자가 입력한 비밀 번호를 가지고, 비밀번호가 맞다면 정보 갱신하고, 그 정보를 바탕으로 MyPage를 통해서 정보 볼 수 있도록
		
		// 사용자에 대한 고유 식별 정보 -> userNo 또는 userId
		// 방법 1. 비즈니스 로직 동작 -> userNo 또는 userId 보내서 식별
		// 방법 2. 비즈니스 로직 동작 -> userId 또는 userPwd 보내서 식별
		// 이미 만들어져 있는 방법 2 사용
		
		String userPwd= request.getParameter("userPwd");	// 사용자가 입력한 password
		
		HttpSession session = request.getSession();
		
		String userId= ((Member)session.getAttribute("member")).getUserId();	// 세션에 있는 userId
		
		MemberService mService = new MemberServiceImpl();
		
		Member m = mService.selectOneMember(userId, userPwd);
		
		
		if(m!=null) {
			session.setAttribute("member", m);	// session 갱신
			RequestDispatcher view=request.getRequestDispatcher("/views/member/myPage.jsp");
			view.forward(request, response);
		}else {
			RequestDispatcher view=request.getRequestDispatcher("/views/member/myPagePasswordCheckFail.jsp");
			view.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



myPage.jsp

<%@page import="kr.or.iei.member.model.vo.Member"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<style>
fieldset {
	width: 300px;
	height: 500px;
	margin: 0 auto;
}
legend {
	text-align: center;
}
</style>


</head>
<body>
	
	<%
		Member m = (Member)session.getAttribute("member");
	%>
	
	
	<form action="/member/memberUpdate.do" method="post">
		<fieldset>
			<legend><%=m.getUserName()%>님의 정보</legend>
			
			ID : <%=m.getUserId() %><br>
			이름 : <%=m.getUserName() %><br>
			비밀번호 : <input type="button" id="pwdChangeBtn" value="비밀번호 변경"><br>
			나이 : <input type="text" size="3" name="age" value="<%=m.getAge() %>"/><br>
			이메일 : <input type="email" name="email" value="<%=m.getEmail() %>"/><br>
			폰번호 : <input type="text" name="phone" value="<%=m.getPhone() %>"/><br>
			주소 : <input type="text" name="address" value="<%=m.getAddress() %>"/><br>
			성별 : 
				<%if(m.getGender()=='M'){ %>
				<input type="radio" name="gender" value="M" checked/><input type="radio" name="gender" value="F" />여
				<%}else{ %>
				<input type="radio" name="gender" value="M" /><input type="radio" name="gender" value="F" checked/>여
				<%} %>
				<br><br>
			취미 <br>
			<%m.getHobby(); 
			// 운동, 등산, 독서
			%>
			
				<input type="checkbox" name="hobby" value="운동" />운동
				<input type="checkbox" name="hobby" value="등산" />등산
				<input type="checkbox" name="hobby" value="독서" />독서<br>
				<input type="checkbox" name="hobby" value="노래"/>노래
				<input type="checkbox" name="hobby" value="댄스"/>댄스
				<input type="checkbox" name="hobby" value="기타"/>기타<br>
				<br><br>
				<input type="submit" id="submitBtn" value="회원정보 변경"/> <button id="mainMoveBtn">메인페이지로</button>
		</fieldset>
	</form>
	
	<!--  패스워트 변경 버튼 팝업 확성화 스크립트 -->
	<script>
		document.getElementById("pwdChangeBtn").onclick=function(){
			window.open("/views/member/memberPasswordChangeWindow.jsp","_blank","width=400px, height=300px");
		};
	</script>
	
	<!-- jQuery 라이브러리 -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>


<script>
	$('#submitBtn').click(function(){
		var result = window.confirm("정말로 변경하시겠습니까?");
		
			if(result)
			{
				return true;
			}else
			{
				return false;
			}
	});
</script>

<!-- 취미 데이터를 선택하기 위한 코드 -->
<script>
	$(function(){
		
		
		//첫번째, 자바의 취미 데이터 문자열을 JavaScript로 가져오기
		var hobby = "<%=m.getHobby()%>";
		
		
		//두번째, 자바스크립트의 저장된 문자열을 배열로 쪼개기 
		// ex) 운동, 등산, 독서 -> [0] = 운동 / [1] = 등산 / [2] = 독서
		// 위에 데이터는 JavaScript 데이터 -> jQuery 형태로
		var $hobbyValues = $(hobby.split(", "));
		
		
		
		//세번째, input 태그에서 type이 checkbox인 녀석들을 찾아라. 혹은 name이 hobby인 태그들을 찾아라.
		var $hobbyElements = $('input[name=hobby]');
		
		
		
		//네번째, 찾은 태그와 찾은 데이터가 일치하면 checked 처리를 하여라.
		
		// DB에 있는 취미 배열 데이를 가지고
		for(var j=0;j<$hobbyValues.length;j++)
			{
			
				//Tag 6개와 비교 하여라.
				for(var i=0;i<$hobbyElements.length;i++)
					{
					
						//비교했을때 일치하는게 있으면
						if($hobbyValues.get(j)==$hobbyElements.get(i).value)
						{
							//checked 속성을 부여 하여라.
							$($hobbyElements.get(i)).prop('checked',true);
							
							//찾았으니 더이상 진행하지 않고, break(중단)
							break;
						}
					}
			}
		
	});
</script>



<script>
	$('#mainMoveBtn').click(function(){
		
		location.replace("/");
		return false; //버튼 태그가 submit 처리 되지 않도록!
	});
</script>


</body>
</html>



MemberUpdateServlet.java

package kr.or.iei.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 kr.or.iei.member.model.service.MemberService;
import kr.or.iei.member.model.service.MemberServiceImpl;
import kr.or.iei.member.model.vo.Member;

/**
 * Servlet implementation class MemberUpdateServlet
 */
@WebServlet("/member/memberUpdate.do")
public class MemberUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MemberUpdateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 한글이 포함되어 있는 경우 -> 인코딩 처리
		request.setCharacterEncoding("UTF-8");
		
		// 페이지에서 보내온 데이터를 저장
		int age = Integer.parseInt(request.getParameter("age"));
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		char gender = request.getParameter("gender").charAt(0);
		String[] hobbyValues = request.getParameterValues("hobby");

		String hobby;
		if (hobbyValues == null) {
			hobby = "없음";
		} else {
			hobby = String.join(", ", hobbyValues);
		}
		// DB에가서 정보를 변경하려면 누구 정보를 변경할 건지에 대한 식별 데이터가 있어야함
		// 해당 유자가 누구인지 session에 있기 때문에 session에서 정보 꺼내오기
		String userId= ((Member)(request.getSession()).getAttribute("member")).getUserId();
		
		
		Member m= new Member(userId, age, email, phone, address, gender, hobby);
		
		// 비즈니스 로직
		MemberService mService= new MemberServiceImpl();
		
		int result = mService.updateOneMember(m);
		
		RequestDispatcher view = request.getRequestDispatcher("/views/member/memberUpdateResult.jsp");
		
		if(result>0) {
			request.setAttribute("updateResult", true);
		}else {
			request.setAttribute("updateResult", false);
		}
		
		view.forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



memberPasswordChangeWindow.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
	#pwdForm{
		width: 250px;
		height: 200px;
		border: 1px solid black;
		margin: 50px auto;
	}
</style>

</head>
<body>
	<div id="pwdForm">
		<form action="/member/memberPwdChange.do" method="post">
			<input type="password" name="pwd" class="b-block w-100" placeholder="현재 패스워드를 작성하세요"><br><br>
			<input type="password" name="new_pwd" class="b-block w-100"  placeholder="변경할 패스워드를 작성하세요"><br><br>
			<input type="password" name="new_pwd_re" class="b-block w-100"  placeholder="변경할 패스워드를 재작성하세요"><br><br>
			<input type="submit"  class="btn btn-primary b-block w-100" value="변경하기">
		</form>
	</div>
</body>
</html>



MemberPwdChangeServlet.java

package kr.or.iei.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 kr.or.iei.member.model.service.MemberService;
import kr.or.iei.member.model.service.MemberServiceImpl;
import kr.or.iei.member.model.vo.Member;

/**
 * Servlet implementation class MemberPwdChangeServlet
 */
@WebServlet("/member/memberPwdChange.do")
public class MemberPwdChangeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MemberPwdChangeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 인코딩
		request.setCharacterEncoding("UTF-8");
		// 현재PW와 변경할PW 값 가져오기
		String pwd = request.getParameter("pwd");
		String newPwd = request.getParameter("new_pwd");

		// 세션에서 해당 유저를 구분할 수 있는 정보를 추출(userId 추출)
		String userId = ((Member) request.getSession().getAttribute("member")).getUserId();

		// 비즈니스 로직 처리
		MemberService mService = new MemberServiceImpl();
		int result = mService.updatePwdMember(userId, pwd, newPwd);
		
		// 변경 성공 : 정상적으로 기존 PW 와 변경PW 입력햇다면 / result =1;
		// 변경 실패 : 기존 PW가 잘못 되었을대 / result =0;
		RequestDispatcher view = request.getRequestDispatcher("/views/member/memberPwdChResult.jsp");
		if(result>0) {
			request.setAttribute("pwdResult", true);
		}else {
			request.setAttribute("pwdResult", false);
		}
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



memberPwdChResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%boolean pwdResult= (boolean)request.getAttribute("pwdResult"); %>
	
	<script>
	<%if(pwdResult){ %>
		window.close();	//팝업 브라우저 닫아라	
		window.opener.alert('비밀번호 변경 성공');
	<%}else{ %>
		alert('비밀번호 변경 실패\n비밀번호를 다시 확인해세요');
		location.replace('/views/member/memberPasswordChangeWindow.jsp');
	<%} %>
	</script>
	
	
</body>
</html>



MemberService.java

package kr.or.iei.member.model.service;

import kr.or.iei.member.model.vo.Member;

public interface MemberService {
	
    public int updateOneMember(Member m);
    
    public int updatePwdMember(String userId, String pwd, String newPwd);
    
}



MemberServiceImpl.java

package kr.or.iei.member.model.service;

import java.sql.Connection;

import kr.or.iei.common.JDBCTemplate;
import kr.or.iei.member.model.dao.MemberDAO;
import kr.or.iei.member.model.vo.Member;
import sun.management.jdp.JdpBroadcaster;

public class MemberServiceImpl implements MemberService {

	private MemberDAO mDAO = new MemberDAO();

	@Override
	public int updateOneMember(Member m) {
		Connection conn = JDBCTemplate.getConnection();
		int result = mDAO.updateOneMember(m, conn);
		
		if(result>0) {
			JDBCTemplate.commit(conn);
		}else {
			JDBCTemplate.rollback(conn);
		}
		
		JDBCTemplate.close(conn);
		
		return result;
	}
    
	@Override
	public int updatePwdMember(String userId, String pwd, String newPwd) {
		Connection conn= JDBCTemplate.getConnection();
		int result = mDAO.updatePwdMember( userId,  pwd,  newPwd, conn);
		
		if(result>0)JDBCTemplate.commit(conn);
		else JDBCTemplate.rollback(conn);
		
		JDBCTemplate.close(conn);
		
		return result;
	}


}



MemberDAO

package kr.or.iei.member.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import kr.or.iei.common.JDBCTemplate;
import kr.or.iei.member.model.vo.Member;

public class MemberDAO {

	public int updateOneMember(Member m, Connection conn) {
		PreparedStatement pstmt= null;
		int result = 0;
		
		String sql="UPDATE MEMBER SET age=?,email=?, phone=?,address=?, gender=?, hobby=? WHERE userid=?";
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, m.getAge());
			pstmt.setString(2, m.getEmail());
			pstmt.setString(3, m.getPhone());
			pstmt.setString(4, m.getAddress());
			pstmt.setString(5, String.valueOf(m.getGender()));
			pstmt.setString(6, m.getHobby());
			pstmt.setString(7, m.getUserId());
			
			result=pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCTemplate.close(pstmt);
		}
		
		return result;
	}


	public int updatePwdMember(String userId, String pwd, String newPwd, Connection conn) {
		PreparedStatement pstmt = null;
		int result = 0;
		
		String sql="UPDATE MEMBER SET userPwd=? WHERE userId=? AND userPwd=?";
		
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, newPwd);
			pstmt.setString(2, userId);
			pstmt.setString(3, pwd);
			
			result = pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCTemplate.close(pstmt);
		}
		return result;
	}				
}
profile
개발자로 매일 한 걸음
post-custom-banner

0개의 댓글