JAVA개념&실습

WEB : [0525] 로그인 세션(Session) 실습

u_SZero 2023. 5. 25. 17:47

! 배워가고 있는 주인장이 작성한 글이니 정보의 정확성에 유의바랍니다 !


 

WebApp13


TestSession01.jsp

 

TestSession01_ok.jsp 페이지에서
이 페이지를 다시 요청할 수 있도록 안내하면서
setssion 의 userId 에 superman 을... userName 에 이가나를 담아서 보낸 상황


String userId = (String)session.getAttribute("userId");                // "superman"
String userName = (String)session.getAttribute("userName");   // "이가나"

 

-- 『session.getAttribute("userId");』는
   Object 타입을 반환하므로
   String 타입으로 변환하는 과정 필요(다운 캐스팅)

추가~!!!
// 세션 시간 변경 설정 -----------------------------------------------------------------------

세션 기본(default) 시간은 1800초.

session.setMaxInactiveInterval(5);


-- 세션이 유지되는 시간을 10초로 설정한 상태
   이로 인해...
   로그인 후 10초 동안 아무 액션도 없는 상태에서...
   다시 페이지 새로고침을 수행하면 로그아웃 처리된 것을 확인할 수 있다.

// ----------------------------------------------------------------------- 세션 시간 변경 설정

 

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	// TestSession01_ok.jsp 페이지에서
	// 이 페이지를 다시 요청할 수 있도록 안내하면서
	// setssion 의 userId 에 superman 을... userName 에 이가나를 담아서 보낸 상황
	String userId = (String)session.getAttribute("userId");			// "superman"
	String userName = (String)session.getAttribute("userName");		// "이가나"
	//-- 『session.getAttribute("userId");』는
	//   Object 타입을 반환하므로
	//   String 타입으로 변환하는 과정 필요(다운 캐스팅)
	
	// 추가~!!!
	// 세션 시간 변경 설정 -----------------------------------------------------------------------
	
	// ※ 세션 기본(default) 시간은 1800초.
	
	session.setMaxInactiveInterval(5);
	//-- 세션이 유지되는 시간을 10초로 설정한 상태
	//   이로 인해...
	//   로그인 후 10초 동안 아무 액션도 없는 상태에서...
	//   다시 페이지 새로고침을 수행하면 로그아웃 처리된 것을 확인할 수 있다.	
	
	// ----------------------------------------------------------------------- 세션 시간 변경 설정
	

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TestSession01.jsp</title>
<link rel="stylesheet" type="text/CSS" href="css/MemberScore.css">

<style type="text/css">
	a {text-decoration: none;}
	.btnMenu
	{
		border: 1px solid gray;
		border-radius: 3px;
		font-size: 8pt;
		width: 60px;
		height: 20px;
	}
</style>

<script type="text/javascript">

	function sendIt()
	{
		// 확인
		//alert("함수 호출 확인~!!!")
		
		//var f = document.getElementById("myForm")
		var f = document.myForm;
		
		if (!f.userId.value)		//id없고 name만 있을 때 값 가져오기
		{
			alert("아이디를 입력해야 합니다~!!!");
			f.userId.focus();
			return;
		}
		
		if (!f.userPwd.value)
		{
			alert("패스워드를 입력해야 합니다~!!!");
			f.userPwd.focus();
			return;
		}
		
		f.submit();
	}

</script>

</head>
<body>

<div>
   <table>
      <tr>
         <td>
            <a href="">
               <button type="button" class="btnMenu btn01">게시판</button>
            </a> |
            
            <%
            if (userId==null)
            {
            %>
            
            <a href="">
               <button type="button" class="btnMenu btn02" disabled="disabled">일정관리</button>
            </a> |
            <a href="">
               <button type="button" class="btnMenu btn02" disabled="disabled">친구관리</button>
            </a> |
            
            <%
            }
            else
            {
            %>
            
            <a href="Sce.jsp">
               <button type="button" class="btnMenu btn01">일정관리</button>
            </a> |
            <a href="Fri.jsp">
               <button type="button" class="btnMenu btn01">친구관리</button>
            </a> |
            
            <%
            }
            %>
         </td>
      </tr>
   </table>
</div>
<br><br>

<div>
	<table>
		<tr>	         
         	<%
         	if(userId==null)
         	{
         	%>
            
			<td>
				<form action="TestSession01_ok.jsp" method="post" name="myForm">
					<table>
						<tr>
							<th>아이디</th>
							<td>
								<input type="text" name="userId" class="txt" style="width: 150px;">
							</td>
						</tr>
						<tr>
							<th>패스워드</th>
							<td>
								<!-- <input type="password"> -->
								<input type="text" name="userPwd" class="txt" style="width: 150px;">
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<button type="button" class="btn" style="width: 100%;"
								onclick="sendIt()">로그인</button>
							</td>
						</tr>
					</table>
				
				</form>
			<%
			}
         	else
         	{
			%>
			<h2><%=userName %>(<%=userId %>)님 환영합니다.</h2>
			<h2>이제, 일정관리와 친구관리 서비스를 이용할 수 있습니다.</h2>
			<p>
				<a href="Logout.jsp">
					<button type="button" class="btnMenu btn01">로그아웃</button>
				</a>
			</p>
			<%
			}
			%>
			</td>
		</tr>
	
	</table>
</div>

</body>
</html>

 

 

 


 

 

TestSession01_ok.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	// TestSession01_ok.jsp
	
	// 이전페이지(TestSession01.jsp)로부터 데이터 수신
	// → userId, userPwd
	String userId = request.getParameter("userId");
	String userPwd = request.getParameter("userPwd");
	
	// DTO 구성 → 로그인 관련 테이블의 데이터와 비교(DAO 활용) → 최종적으로 로그인 액션 처리
	String tblMemberId = "superman";
	String tblMemberPwd = "123456";
	String tblMemberName = "이가나";
	
	if(userId.equals(tblMemberId) && userPwd.equals(tblMemberPwd))
	{
		// 로그인 액션 처리
		session.setAttribute("userId", userId);			//-- userId - superman
		session.setAttribute("userName", tblMemberName);	//-- userName - 이가나
		
		// 클라이언트가 페이지를 다시 요청할 수 있도록 안내
		response.sendRedirect("TestSession01.jsp");
	}
	
	
	

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TestSession01_ok.jsp</title>
<link rel="stylesheet" type="text/CSS" href="css/main.css">
</head>
<body>

<h1>로그인 실패~!!!</h1>

<a href="TestSession01.jsp">로그인 페이지로 돌아가기~!!!</a>

</body>
</html>

 

 


 

 

Logout.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	// Logout.jps
	//-- 세션의 내용을 없애서 로그아웃 처리
	
	session.removeAttribute("userId");
	session.removeAttribute("userPwd");
	session.removeAttribute("userName");
	//-- 세션의 사용자 아이디와 사용자 이름 제거
	
	// 기존 세션에 저장되어 있는 모~~~ 든 항목을 제거하고
	// 세션을 초기화
	session.invalidate();
	
	// 클라이언트에게 다시 로그인 페이지를 요청할 수 있도록 안내
	response.sendRedirect("TestSession01.jsp");

%>

 

 

 


! 배워가고 있는 주인장이 작성한 글이니 정보의 정확성에 유의바랍니다 !