프로젝트

프로젝트진행중 ( 로그인시 index에 정보몇개전달 , id/pw찾기)

동곤일상 2025. 5. 13. 22:54
반응형

1) 로그인관련(doLogin)

 

 

 

1-1)doLogin(로그인)성공시  session속성 추가로등록

if(pass.equals(dbPw)
					//BCrypt.checkpw(pass, pro.getProfessorPassword())
						){//로그인성공
					session.setAttribute("login", dbId);
					if(dbId.contains("s")) {
						StudentDao dao = new StudentDao();
						Student student = dao.selectOne(dbId);
						session.setAttribute("m", student);
					}
					else {
						ProfessorDao dao = new ProfessorDao();
						Professor professor = dao.selectOne(dbId);
						session.setAttribute("m", professor);
					}
					request.setAttribute("msg", dbName+"님이 로그인 하셨습니다");
					request.setAttribute("url","index");

				}

메인화면(index)에 사진도 넣고 정보등을 넣어주려면 객체전체를 넘겨줘야함

 

 

dist/pages/index.jsp

	<li class="nav-item dropdown user-menu"><a href="#"
						class="nav-link dropdown-toggle" data-bs-toggle="dropdown"> 
						<!-- 교수와학생인경우 컬럼명이다르므로 삼항연산자를활용해처리 -->
						<c:set var="img" value="${fn:contains(sessionScope.login, 's') ? m.studentImg : m.professorImg}" />
						<img 
							src="${path}/dist/assets/picture/${img}"
							class="user-image rounded-circle shadow" alt="User Image" /> <span
							class="d-none d-md-inline" style="font-size: 20px">${sessionScope.login}님 반갑습니다</span>
					</a>
						<ul class="dropdown-menu dropdown-menu-lg dropdown-menu-end">
							<!--begin::User Image-->
							<c:set var="img" value="${fn:contains(sessionScope.login, 's') ? m.studentImg : m.professorImg}" />
							<li class="user-header text-bg-primary"><img
								src="${path}/dist/assets/picture/${img}"
								class="rounded-circle shadow" alt="User Image" /> <%-- 세션 정보에 따라 이름 출력 --%>
								<c:if test="${fn:contains(sessionScope.login, 's')}">
								<fmt:formatDate value="${m.studentBirthday}" pattern="YYYY-MM-dd" var="birth"/>
									<p>${m.studentName}<small>${birth}</small>
									</p>
								</c:if> <c:if test="${not fn:contains(sessionScope.login, 's')}">
								<fmt:formatDate value="${m.professorBirthday}" pattern="YYYY-MM-dd" var="birth"/>
									<p>${m.professorName}<small>${birth}</small>
									</p>
								</c:if></li>

학생 ,교수인경우에 컬럼명이다르므로 core태그의if문 <c:if>를 활용해 각각 다른컬럼을 나타내도록했다

 

 

 


1-2) doLogin (로그인화면)접근

 

로그인이되어있다면 (session정보가있다면 index로보내버림)

@RequestMapping("doLogin") //로그인상태로접근불가능
	public String doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String login = (String)session.getAttribute("login");
		if(login==null) {
			return "mypage/doLogin";
		}
		else {
			request.setAttribute("msg", "로그아웃을하세요");
			request.setAttribute("url","index");
			return "alert";
		}
		
	}

로그인이 되어있다면 doLogin에 어떠한방법으로도접근할수없음!

 

 

2) findId(아이디찾기)

 

doLogin의 아이디찾기버튼을 통해 접근가능

 

/mypage/findId.jsp

body부분만 뽑아옴

<body>
    <div class="card">
        <h4 class="text-center mb-4">아이디 찾기</h4>
        <form action="findIdProcess">      
     
        <div class="mb-3">
            <label for="name" class="form-label">이름</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="이름 입력">
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">이메일</label>
            <input type="email" class="form-control" id="email" name="email"  placeholder="이메일 입력">
        </div>
        <button class="btn btn-custom w-100 mb-3">아이디 찾기</button>
        <div class="text-center">
            <a href="close" class="btn-link-custom">로그인 화면으로 돌아가기</a>
        </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

이름,이메일을 입력받아서 아이디찾기를 누른다면 findIdProcess라는 이름을 찾아갈것임(매핑)

 

로그인화면으로 돌아가기에 매핑되어있는 close를 먼저보여주겠음

 

 

1-1)  findIdProcess매핑부분

 

mypageController.java

@RequestMapping("findIdProcess")
	public String findIdProcess(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String email = request.getParameter("email");

		ProStuDao proStuDao = new ProStuDao();
		String id = proStuDao.findId(name, email);
		if(id==null) {
			request.setAttribute("msg", "입력된정보가없어요");			
			return "idSearch";
		}
		else {
			request.setAttribute("msg", "id : "+id); //추후에는 이메일로보내는거까지??
			request.setAttribute("id", id);
			return "idSearch";
		}
		
	}

findIdProcess : form을 통해 name,email가 파라미터로넘어옴

ProStuDao라는 professor와 Student를 한번에처리할수잇는Dao의

findId메서드로 넘겨줌 

 

ProStuDao의 findId메서드부분

public String findId(String name , String email) {
		SqlSession conn = MyBatisConnection.getConnection();
		FindIdDto dto = new FindIdDto();
		dto.setProfessorEmail(email);
		dto.setProfessorName(name);
		dto.setStudentEmail(email);
		dto.setStudentName(name);
		
		try {
			String id = conn.selectOne("prostu.findId",dto);
			return id;	
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(conn);
		}
		return null;
		
	}

FindIdDto라는 4개의속성을 가진 Dto에 해당값들을 넣어준 후

 

ProStu.xml

해당쿼리로 넘긴다 

UNION을 할 시 두개의결과가 합쳐지므로 조건에맞는값 하나만 꺼낼수잇게됨

<select id="findId" resultType="String" parameterType="FindIdDto">
	SELECT student_id 
	FROM student
	WHERE student_name = #{studentName} AND student_email=#{studentEmail}
	UNION
	SELECT professor_id 
	FROM professor
	WHERE professor_name = #{professorName} AND professor_email=#{professorEmail};
	</select>

 

 

idSearch.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
alert("${msg}")
//requestScope.msg
opener.document.f.id.value = "${id}"
//requestScope.id
self.close();
</script>

아이디찾기가 끝나면 발생하는 페이지

request로넘어온 msg를 띄운 후

넘어온 id를 opener의 id value값에 채워줌( 실패시 빈값)

그 후 창을닫아줌(findId창)


 

1-2) close매핑부분 

로그인화면으로 돌아가기 클릭시발생


@RequestMapping("close")
	public String close(HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("msg", request.getAttribute("msg"));
		return "close";
	}

mypage/close.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<script>
if(${msg!=null}){
	alert("${msg}");
}
	self.close();
</script>

msg로넘어온게없다면 무시하고
현재창을닫아줌

 


3) findPw (비밀번호찾기 findId보다 구조적으로복잡)

 

3-1) 화면과 비밀번호찾기의 과정들

 

/mypage/findId.jsp

body부분만!!!

<body>
    <div class="card">
        <h4 class="text-center mb-4">비밀번호 찾기</h4>
        <form action="findPwProcess" name="f" method="post">
        <div class="mb-3">
            <label for="id" class="form-label">아이디</label>
            <input type="text" class="form-control" id="id" name="id" placeholder="아이디 입력">
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">이메일</label>
            <input type="email" class="form-control" id="email"  name="email" placeholder="이메일 입력">
        </div>
        <button class="btn btn-custom w-100 mb-3">비밀번호 찾기</button>
        <div class="text-center">
            <a href="close"  class="btn-link-custom">로그인 화면으로 돌아가기</a>
        </div>
        </form>     
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

close는 위에 설명이있으니 생략

 

findPwProcess매핑부분

	@RequestMapping("findPwProcess")
	public String findPwProcess(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String email = request.getParameter("email");
		String pw = new ProStuDao().findPw(id,email);
		if(pw==null) {
			request.setAttribute("msg", "입력된정보가없어요");			
			return "mypage/close";
		}
		else {
			request.setAttribute("msg", "비밀번호는"+pw+"입니다");
			request.setAttribute("id", id);
			request.setAttribute("pw", pw);
			//return "mypage/pwUpdate";
			return "mypage/alertPw";
		}
	}

폼으로넘어온 id email을 ProStuDao의 findPw로 전달해 pw를 반환받음

그 pw가 null이라면 입력된정보가없다고 띄운후 close로이동

 

pw를 찾았다면

msg를 띄운후 ( 추후에는 띄운후 이메일로보낼거임)

id와 pw를 request속성으로 등록 후

alertPw 로보낸다


ProStuDao의 findPw메서드(아이디,이메일로비번찾기)

public String findPw(String id , String email) {
		SqlSession connection = MyBatisConnection.getConnection();
		FindPwDto dto = new FindPwDto();
		dto.setProfessorEmail(email);
		dto.setProfessorId(id);
		dto.setStudentEmail(email);
		dto.setStudentId(id);
		try {
			return connection.selectOne("prostu.findPw",dto);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(connection);
		}
		return null;
	}

FindPwDto는 저기 set프로퍼티를보면알겟지만 이메일과아이디로이루어져있음(학생,교수모두)

 

ProStu.xml

findPw부분

<select id="findPw" resultType="String" parameterType="FindPwDto">
	SELECT student_password 
	FROM student
	WHERE student_id = #{studentId} AND student_email=#{studentEmail}
	UNION
	SELECT professor_password
	FROM professor
	WHERE professor_id = #{professorId} AND professor_email=#{professorEmail};
	</select>

조건에 맞는값만 출력해줄거임

 


3-2 )비밀번호찾기성공시 발생하는부분들

alertPw.jsp

보이지않는페이지임 (그냥 값만넘겨주는 다리느낌)

 

form에 전달받은request속성을 넣어준후 바로 submit처리한다

(pwUpdate로 매핑시킴)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Alert</title>
</head>
<body>
    <form action="pwUpdate" name="f" method="post">
        <input type="hidden" name="id" value="${requestScope.id}">
        <input type="hidden" name="pw" value="${requestScope.pw}">
    </form>
    <script>
        // 메시지 표시
        var msg = "${requestScope.msg}";
        if (msg) {
            alert(msg);
        }
        document.f.submit();
    </script>
</body>
</html>

 

mypage/pwUpdate.jsp

<body>
    <div class="card">
        <h4 class="text-center mb-4">비밀번호 변경</h4>
        <form action="pw" method="post" onsubmit="return input_check(this)">
           
            <input type="hidden" value="${param.id}" name="id">
            <!-- 현재비밀번호는 비밀번호찾기가성공적으로됐다면 자동으로 입력될것임 -->
            <div class="mb-3">
                <label for="pw" class="form-label">현재 비밀번호</label>
                <input type="password" class="form-control" id="pw" name="pw" value="${param.pw}">
            </div>
            
            <div class="mb-3">
                <label for="cPw" class="form-label">변경할 비밀번호</label>
                <input type="password" class="form-control" id="cPw" name="cPw" placeholder="변경할 비밀번호">
            </div>
            
            <div class="mb-3">
                <label for="cPw2" class="form-label">변경할 비밀번호 재입력</label>
                <input type="password" class="form-control" id="cPw2" placeholder="재입력">
            </div>
            
            <button class="btn btn-custom w-100 mb-3">비밀번호 변경</button>
            <div class="text-center">
                <a href="close" class="btn btn-link-custom">비밀번호를 나중에 바꾸고 싶으면 클릭!</a>
            </div>
        </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript">
        function input_check(t) {
            if (t.cPw.value.trim() != t.cPw2.value.trim()) {
                alert("변경할 비밀번호와 재입력한 비밀번호가 일치하지 않습니다.");
                t.cPw2.focus();
                return false;
            }
            return true;
        }
      

    </script>
</body>

간단히 remind해보면

request로넘어온 id를 hidden을통해 화면에보이지않고 가지고만있는다

 

현재pw는 찾은 pw가 들어가있게끔 설정

바꿀비번 , 바꿀비번재입력 을 받아 pw로 폼을넘긴다

(id,pw,cPw가 넘어가게될거임)

(둘이 다르면 submit할 시 폼이넘어가지않을거임)

 

비밀번호를 나중에바꾸고싶으면 클릭을 누르면 close로이동

 

 

pw매핑부분(mypageController)

//pwUpdate에서 넘어오는곳(비밀번호처리만담당)
	@RequestMapping("pw")
	public String pw(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String cPw = request.getParameter("cPw");
		System.out.println(id);
		System.out.println(pw);
		System.out.println(cPw);
		String msg = "비밀번호변경실패";
		boolean updatePw = new ProStuDao().updatePw(id,pw,cPw);
		if(updatePw) {
			msg = "비밀번호변경완료!!!";
		}
		
		request.setAttribute("msg",msg);
		return "mypage/close";
	}

updatePw로 폼으로전달받은값 모두를 넣어 updater결과를 반환

true -> msg : 비밀번호변경완료

false -> msg:비밀번호변경실패

속성등록후 close반환

 

 

ProStuDao의 updatePw메서드

update문은 union처리가불가능하므로 Dto를 학생,교수 따로만들어서

update문을 실행했음 (update성공시에만 true반환)

public boolean updatePw(String id, String pw, String cPw) {
		SqlSession connection = MyBatisConnection.getConnection();
		UpdateProPwDto pDto = new UpdateProPwDto();
		UpdateStuPwDto sDto = new UpdateStuPwDto();
		
		try {
			if(id.contains("p")) {
				pDto.setProfessorId(id);
				pDto.setProfessorPassword(pw);
				pDto.setProfessorNewPassword(cPw);
				if(connection.update("updateProPw",pDto)>0) {
				connection.commit();
					return true;
				}
			}
			else {
				sDto.setStudentId(id);
				sDto.setStudentPassword(pw);
				sDto.setStudentNewPassword(cPw);
				if(connection.update("updateStuPw",sDto)>0) {
					connection.commit();
					return true;
				}
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			MyBatisConnection.close(connection);
		}
		return false;
	}

 

ProStu.xml의 updateStuPw , updateProPw

<update id="updateStuPw" parameterType="UpdateStuPwDto" >
		update student set student_password=#{studentNewPassword}
		where student_password=#{studentPassword} and student_id=#{studentId}
	</update>
	
	<update id="updateProPw" parameterType="UpdateProPwDto">
		update professor set professor_password=#{professorNewPassword}
		where professor_password=#{professorPassword} and professor_id=#{professorId}
	</update>

아이디비번이 일치한다면 새로입력받은 비밀번호로업데이트!

 

 

 

3-3) 비밀번호찾기(findId)과정  사진!!

1111을 입력했음