ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JSP] 007. 쿠키(Cookie)와 세션(Session) (2)
    SsY/Class 2023. 5. 26. 12:50
    728x90
    세션(Session)
    - WebApp14
    • TestSession01 & TestSession02 & TestSession03
    • TestSession01
    <%@ page contentType="text/html; charset=UTF-8"%>
    <!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">
    	#next { width: 100px;}
    </style>
    
    <script type="text/javascript">
    	function sendIt()
    	{
    		// 확인
    		//alert("함수호출테스트");
    		
    		//form name 으로 가져오는 방법
    		//var f = document.myForm;
    		//form 순서로 가져오는 방법
    		var f = document.forms[0];
    		
    		// 이름 입력 확인
    		if (!f.userName.value)
    		{
    			alert("이름을 입력하세요");
    			f.userName.focus();
    			return;
    		}
    		
    		// 전화번호 확인
    		if (!f.userTel.value)
    		{
    			alert("전화번호를 입력하세요");
    			f.userTel.focus();
    			return;
    		}
    		
    		// 폼 제출
    		f.submit();		
    	}
    </script>
    
    </head>
    <body>
    
    <div>
    <!-- 
    	○	TestSession01.jsp 에서 TestSession02.jsp 로
    	    이름과 전화번호를 입력받아 전송
    	    
    	    TestSession02.jsp 에서 TestSession03.jsp 로
    	    아이디와 패스워드를 입력받고
    	    앞에서 전달받은 이름과 전화번호를 함께 전송
    	    
    	    TestSession03.jsp 에서 전달받은 이름, 전화번호 , 아이디, 패스워드 출력
    	    
    	    01 ─────────> 02 ─────────> 03
    	    이름, 전화번호         아이디, 패스워드       이름, 전화번호, 아이디, 패스워드
    	    입력                   입력                   출력
    	                           - getParameter         - getAttribute
    	
    	※ 즉, 01 에서 02 로 넘겨받을 땐 getParameter
    	   02 에서 03 으로 넘겨받을 땐 getParameter 과 getAttribute 로 세션 활용
    	   01 에서 03 으로 넘겨줄 수 없기 때문에 세션(session)에 저장
    	   
    	※ session 외에 input 태그 hidden 속성을 이용한 정보 전달 가능
    -->	   
    </div>
    
    <div>
    	<h1>이름과 전화번호 (TestSession01.jsp)</h1>
    	<hr>
    </div>
    <br>
    <div>
    	<form action="TestSession02.jsp" method="post" name="myForm">
    		<table class="table">
    			<tr>
    				<th colspan="2">본인 확인</th>
    			<tr>
    			<tr>
    				<th>이름</th>
    				<td>
    					<input type="text" class="txt" name="userName"/>
    				</td>
    			</tr>
    			<tr>
    				<th>전화번호</th>
    				<td>
    					<input type="text" class="txt" name="userTel"/>
    				</td>
    			</tr>
    			<tr>
    				<td colspan="2">
    					<button type="button" class="btnMenu btn01" id="next" onclick="sendIt()"> >> 다음 </button>
    				</td>
    			</tr>
    		</table>
    	</form>
    </div>
    
    </body>
    </html>
    더보기
    <%@ page contentType="text/html; charset=UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSession01_1.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/MemberScore.css">
    <style type="text/css">
    	#next { width: 100px;}
    </style>
    
    <script type="text/javascript">
    	function sendIt()
    	{
    		// 확인
    		//alert("함수호출테스트");
    		
    		//form name 으로 가져오는 방법
    		//var f = document.myForm;
    		//form 순서로 가져오는 방법
    		var f = document.forms[0];
    		
    		// 이름 입력 확인
    		if (!f.uName.value)
    		{
    			alert("이름을 입력하세요");
    			f.uName.focus();
    			return;
    		}
    		
    		// 전화번호 확인
    		if (!f.uTel.value)
    		{
    			alert("전화번호를 입력하세요");
    			f.uTel.focus();
    			return;
    		}
    		
    		// 폼 제출
    		f.submit();		
    	}
    </script>
    
    </head>
    <body>
    
    <div>
    <!-- 
    	○	TestSession01.jsp 에서 TestSession02.jsp 로
    	    이름과 전화번호를 입력받아 전송
    	    
    	    TestSession02.jsp 에서 TestSession03.jsp 로
    	    아이디와 패스워드를 입력받고
    	    앞에서 전달받은 이름과 전화번호를 함께 전송
    	    
    	    TestSession03.jsp 에서 전달받은 이름, 전화번호 , 아이디, 패스워드 출력
    	    
    	    01 ─────────> 02 ─────────> 03
    	    이름, 전화번호         아이디, 패스워드       이름, 전화번호, 아이디, 패스워드
    	    입력                   입력                   출력
    	                           - getParameter         - getAttribute
    	
    	※ 즉, 01 에서 02 로 넘겨받을 땐 getParameter
    	   02 에서 03 으로 넘겨받을 땐 getParameter 과 getAttribute 로 세션 활용
    	   01 에서 03 으로 넘겨줄 수 없기 때문에 세션(session)에 저장
    -->	   
    </div>
    
    <div>
    	<h1>회원가입 (TestSession01_1.jsp)</h1>
    	<hr>
    </div>
    <br>
    <div>
    	<form action="TestSession02.jsp" method="post" name="myForm">
    		<table class="table">
    			<tr>
    				<th colspan="2">본인 확인</th>
    			<tr>
    			<tr>
    				<th>이름</th>
    				<td>
    					<input type="text" class="txt" name="uName"/>
    				</td>
    			</tr>
    			<tr>
    				<th>전화번호</th>
    				<td>
    					<input type="text" class="txt" name="uTel"/>
    				</td>
    			</tr>
    			<tr>
    				<td colspan="2">
    					<button type="button" class="btnMenu btn01" id="next" onclick="sendIt()"> >> 다음 </button>
    				</td>
    			</tr>
    		</table>
    	</form>
    </div>
    
    </body>
    </html>

    • TestSession02
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 이전 페이지(TestSession01.jsp)로부터 데이터 수신
    	// → userName, userTel
    	
    	request.setCharacterEncoding("UTF-8");
    	
    	String userName = request.getParameter("userName");
    	String userTel = request.getParameter("userTel");
    	
    	// check 
    	// 추가 - 전달 받은 데이터 세션에 저장 
    	session.setAttribute("userName", userName);
    	session.setAttribute("userTel", userTel);
    	
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSession02.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/MemberScore.css">
    <style type="text/css">
    	#next { width: 100px;}
    </style>
    
    <script type="text/javascript">
    	function sendIt()
    	{
    		// 확인
    		//alert("함수호출테스트");
    
    		//form 순서로 가져오는 방법
    		var f = document.forms[0];
    		
    		// 이름 입력 확인
    		if (!f.userId.value)
    		{
    			alert("이름을 입력하세요");
    			f.userId.focus();
    			return;
    		}
    		
    		// 전화번호 확인
    		if (!f.userPwd.value)
    		{
    			alert("전화번호를 입력하세요");
    			f.userPwd.focus();
    			return;
    		}
    		
    		// 폼 제출
    		f.submit();		
    	}
    </script>
    
    </head>
    <body>
    
    <div>
    <!-- 
    	○	TestSession01.jsp 에서 TestSession02.jsp 로
    	    이름과 전화번호를 입력받아 전송
    	    
    	    TestSession02.jsp 에서 TestSession03.jsp 로
    	    아이디와 패스워드를 입력받고
    	    앞에서 전달받은 이름과 전화번호를 함께 전송
    	    
    	    TestSession03.jsp 에서 전달받은 이름, 전화번호 , 아이디, 패스워드 출력
    	    
    	    01 ─────────> 02 ─────────> 03
    	    이름, 전화번호         아이디, 패스워드       이름, 전화번호, 아이디, 패스워드
    	    입력                   입력                   출력
    	                           - getParameter         - getAttribute
    	
    	※ 즉, 01 에서 02 로 넘겨받을 땐 getParameter
    	   02 에서 03 으로 넘겨받을 땐 getParameter 과 getAttribute 로 세션 활용
    	   01 에서 03 으로 넘겨줄 수 없기 때문에 세션(session)에 저장
    -->	   
    </div>
    
    <div>
    	<h1>아이디와 패스워드 (TestSession02.jsp)</h1>
    	<hr>
    </div>
    <br>
    <div>
    	<form action="TestSession03.jsp" method="post" name="myForm">
    		<table class="table">
    			<tr>
    				<th colspan="2">본인 확인</th>
    			<tr>
    			<tr>
    				<th>아이디</th>
    				<td>
    					<input type="text" class="txt" name="userId"/>
    				</td>
    			</tr>
    			<tr>
    				<th>패스워드</th>
    				<td>
    					<input type="text" class="txt" name="userPwd"/>
    				</td>
    			</tr>
    			<tr>
    				<td colspan="2">
    					<button type="button" class="btnMenu btn01" id="next" onclick="sendIt()"> >> 다음 </button>
    				</td>
    			</tr>
    		</table>
    <%-- 		
    		※ session 외에 input 태그 hidden 속성을 이용한 정보 전달 가능
    		<input type="hidden" name="userName" value="<%=userName %>">
    		<input type="hidden" name="userTel" value="<%=userTel %>">
    --%>
    	</form>
    </div>
    
    </body>
    </html>
    더보기
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 이전 페이지로부터 데이터 수신
    	request.setCharacterEncoding("UTF-8");
    
    	String name = request.getParameter("uName");
    	String tel = request.getParameter("uTel");
    	
    	// DTO 구성 → 로그인 관련 테이블의 데이터와 비교(DAO 활용) → 최종적으로 로그인 액션 처리
    	// 실습편의상 생략하여 아래와같이 데이터를 얻었다는 가정하에 진행
    	String tblMemberName = "다금바리";
    	String tblMemberTel = "010-9999-9999";
    	
    	// 기존 회원 아니라는 전제하에 가입 진행
    	if(!tblMemberName.equals(name) && !tblMemberTel.equals(tel))
    	{
    		// 세션에 데이터 저장
    		session.setAttribute("uName", name);
    		session.setAttribute("uTel", tel);
    	}
    	
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSession02_1.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/MemberScore.css">
    <style type="text/css">
    	#next { width: 100px;}
    </style>
    
    <script type="text/javascript">
    	function sendIt()
    	{
    		// 확인
    		//alert("함수호출테스트");
    		
    		var f = document.myForm;
    		
    		// 아이디 입력 확인
    		if (!f.uId.value)
    		{
    			alert("아이디를 입력하세요");
    			f.uId.focus();
    			return;
    		}
    		
    		// 패스워드 확인
    		if (!f.uPwd.value)
    		{
    			alert("패스워드를 입력하세요");
    			f.uPwd.focus();
    			return;
    		}
    		
    		// 폼 제출
    		f.submit();		
    	}
    </script>
    </head>
    <body>
    
    <div>
    	<h1>회원가입 (TestSession02.jsp)</h1>
    	<hr>
    </div>
    <br>
    <div>
    	<form action="TestSession03.jsp" method="post" name="myForm">
    		<table class="table">
    			<tr>
    				<th colspan="2"> 정보 입력 </th>
    			<tr>
    			<tr>
    				<th>아이디</th>
    				<td>
    					<input type="text" class="txt" name="uId"/>
    				</td>
    			</tr>
    			<tr>
    				<th>패스워드</th>
    				<td>
    					<input type="password" class="txt" name="uPwd"/>
    				</td>
    			</tr>
    			<tr>
    				<td colspan="2">
    					<button type="button" class="btnMenu btn01" id="next" onclick="sendIt()"> >> 완료 </button>
    				</td>
    			</tr>
    		</table>
    	</form>
    </div>
    
    
    </body>
    </html>

    • TestSession03
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 이전 페이지(TestSession02.jsp)로부터 데이터 수신
    	// → userId, userPwd (+userName, userTel)
    	
    	request.setCharacterEncoding("UTF-8");
    
    	String userId = request.getParameter("userId");
    	String userPwd = request.getParameter("userPwd");
    	
    	//String userName = request.getParameter("userName");
    	//String userTel = request.getParameter("userTel");
    	//			↓ 수정 - 세션에 저장된 값 가져오기 
    	String userName = (String)session.getAttribute("userName");
    	String userTel = (String)session.getAttribute("userTel");
    	
    	session.removeAttribute("userName");
    	session.removeAttribute("userTel");
    	//--> 세션에 담은 값을 지워도 해당 영역에서는 보인다.
    	//    다만 다음 페이지에 가서 세션 값을 찾으면 안보인다~
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSession03.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/MemberScore.css">
    
    </head>
    <body>
    
    <div>
    	<h2>이름, 전화번호, 아이디, 패스워드 출력 (TestSession03.jsp)</h2>
    	<hr>
    </div>
    <br>
    
    <div>
    	<!-- <h4>이름 : 홍길동</h4> -->
    	<h4>이름 : <%=userName %></h4>
    	<!-- <h4>전화번호 : 010-1212-3434</h4> -->
    	<h4>전화번호 : <%=userTel %></h4>
    	<!-- <h4>아이디 : hong</h4> -->
    	<h4>아이디 : <%=userId %></h4>
    	<!-- <h4>패스워드 : 123456</h4> -->
    	<h4>패스워드 : <%=userPwd %></h4>
    </div>
    
    </body>
    </html>
    더보기
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 이전 페이지 (TestSession03.jsp)로부터 데이터 수신
    	request.setCharacterEncoding("UTF-8");
    
    	String id = request.getParameter("uId");
    	String pwd = request.getParameter("uPwd");
    
    	// 세션에서 값 가져오기
    	String name = (String)session.getAttribute("uName");
    	String tel = (String)session.getAttribute("uTel");
    	
    	// 세션에 값 저장해주기
    	session.setAttribute("uId", id);
    	session.setAttribute("uPwd", pwd);
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSession03_1.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/MemberScore.css">
    <style type="text/css">
    	#next { width: 100px;}
    </style>
    </head>
    <body>
    
    <div>
    	<h1>회원가입 (TestSession03.jsp)</h1>
    	<hr>
    </div>
    <br>
    <div>
    	<form action="TestSession03.jsp" method="post" name="myForm">
    		<table class="table">
    			<tr>
    				<th colspan="2"> 회원가입 완료 </th>
    			<tr>
    			<tr>
    				<th>이름</th>
    				<td>
    					<input type="text" class="txt" name="uName" value=<%=name %> disabled="disabled"/>
    				</td>
    			</tr>
    			<tr>
    				<th>전화번호</th>
    				<td>
    					<input type="text" class="txt" name="uTel" value=<%=tel %> disabled="disabled"/>
    				</td>
    			</tr>
    			<tr>
    				<th>아이디</th>
    				<td>
    					<input type="text" class="txt" name="uId" value=<%=id %> disabled="disabled"/>
    				</td>
    			</tr>
    			<tr>
    				<th>패스워드</th>
    				<td>
    					<input type="text" class="txt" name="uPwd" value=<%=pwd %> disabled="disabled"/>
    				</td>
    			</tr>
    		</table>
    	</form>
    </div>
    
    
    </body>
    </html>

    쿠키(Cookie)
    WebApp15
    • TestSetCookie & TestGetCookie & TestRemoveCookie
    • TestSetCookie
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	request.setCharacterEncoding("UTF-8");
    
    	// 쿠키 생성 (서버에 생성된 쿠키)
    	Cookie c = new Cookie("cookieTest","studyCookie");
    	
    	// 쿠키 설정 (서버에 생성된 쿠키에 대한 설정)
    	c.setMaxAge(3600);		//-- 쿠키 1시간 유지
    							//-- 설정하지 않으면 브라우저 종료시에 사라짐
    	
    	// 쿠키 추가 (서버에서 생성되고 설정된 쿠키를 클라이언트에 전달(심어놓기))
    	response.addCookie(c);
    	
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestSetCookie.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
    <body>
    
    <div>
    	<h1>쿠키 설정 및 추가</h1>
    	<hr />
    </div>
    
    <div>
    	<a href="TestGetCookie.jsp"><button type="button" class="btn">쿠키 정보 확인</button></a>
    	<a href="TestRemoveCookie.jsp"><button type="button" class="btn">쿠키 정보 삭제</button></a>
    </div>
    
    </body>
    </html>

    쿠키 Cookie 클래스 추가
    쿠키 상자 -> 배열 반환


    • TestGetCookie
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	request.setCharacterEncoding("UTF-8");
    
    	//check
    	Cookie[] cookieBox = request.getCookies();
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestGetCookie.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <style type="text/css">
    	th {text-align: left;}
    </style>
    </head>
    <body>
    
    <div>
    	<h1>쿠키 정보 얻어내기</h1>
    	<hr />
    </div>
    
    <div>
    	<table class="table">
    		<tr>
    			<th style="width: 50%;">쿠키이름</th>
    			<th style="width: 50%;">쿠키 값</td>
    		</tr>
    		<%
    		for (Cookie singleCookie: cookieBox)
    		{
    		%>
    		<tr>
    			<td><%=singleCookie.getName() %></td>
    			<td><%=singleCookie.getValue() %></td>
    		</tr>
    		<%
    		}
    		%>
    	</table>
    </div>
    
    <div>
    	<a href="TestSetCookie.jsp"><button type="button" class="btn">쿠키 정보 설정</button></a>
    	<a href="TestRemoveCookie.jsp"><button type="button" class="btn">쿠키 정보 삭제</button></a>
    </div>
    
    </body>
    </html>

    • TestRemoveCookie
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 쿠키 정보에 한글이 들어있을 경우를 대비한 인코딩
    	request.setCharacterEncoding("UTF-8");
    
    	// 쿠키를 제거하는 방법
    	// ~서버쪽의 쿠키~
    	// 비어있는 내용으로 기존의 쿠키를 덮어쓰기 하는 개념
    	Cookie killCookie = new Cookie("cookieTest","");
    	// 덮어쓸 쿠키 유지시간을 0초로!
    	killCookie.setMaxAge(0);
    	
    	// 쿠키를 클라이언트에 세팅
    	response.addCookie(killCookie);
    	//-- 처음 쿠키를 구성할 떄에도 『addCookie()』 로 처리하였기 때문에
    	//   삭제하는 과정에서도 『addCookie()』 로 처리해야 안정적으로 삭제.
    	//   즉, 내용이 포함된 쿠키를 심었다가...
    	//   이번에는 내용이 비어있는 쿠키를 심는다는 개념
    	
    	// ※ 여기서 쿠키 삭제는 클라이언트 입장에서의 삭제이다.
    	//    한 명의 클라이언트가 쿠키를 삭제했다고 해서
    	//    다른 클라이언트들의 쿠키도 삭제되면 안되기 때문에
    	//    이 쿠키의 정보는 (브라우저가...) 로컬 PC 에서 컨트롤하게 된다.
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestRemoveCookie.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
    <body>
    
    <div>
    	<h1>쿠키 정보 삭제하기</h1>
    	<hr />
    </div>
    
    <div>
    	<h2>성공적으로 쿠키를 제거했습니다.</h2>
    </div>
    
    <div>
    	<!-- 버튼 타입속성 미 지정시 default 값 submit -->
    	<a href="TestSetCookie.jsp"><button type="button" class="btn">쿠키 정보 설정</button></a>
    	<a href="TestGetCookie.jsp"><button type="button" class="btn">쿠키 정보 확인</button></a>
    </div>
    
    </body>
    </html>

    • TestApplication.jsp
      - 스코프 관찰
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%
    	// 접속자 수 처리
    	int n = 0;
    
    	// 내장객체 *application*
    	String count = (String)application.getAttribute("count");
    	
    	if(count != null)
    	 n = Integer.parseInt(count);
    	
    	n++;
    	application.setAttribute("count", Integer.toString(n));
    
    	// 웹 서버 실제 경로
    	String realPath = application.getRealPath("/");
    	
    	// 실제 접속자 주소 처리(콘솔 창 → 로그 기록을 통해 확인할 수 있도록 구성)
    	application.log("접속자 : " + request.getRemoteAddr());
    	
    	
    	
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>TestApplication.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
    <body>
    
    <div>
    	<h1>Application 을 활용한 접속자 수 체크</h1>
    	<hr>
    </div>
    
    <div>
    	<h2>총 접속자: <%=n %></h2>
    	<h2>웹 서버 실제 경로 : <%=realPath %></h2>
    </div>
    
    </body>
    </html>
    
    <!-- 본인이 localhost 로 접근하면 정보: 접속자 : 0:0:0:0:0:0:0:1 로 보임 -->
    728x90
Designed by planet-si