JSP - chapter8(1)

ZiSoOm·2021년 8월 5일
0

JSP

목록 보기
12/12

쿠키

  • 쿠키의 구성 <이름, 값>
    이름 : 각각의 쿠키를 구별
    값 : 쿠키의 이름과 관련된 값

쿠키 path

  • path 지정 안함 : 쿠키를 생성했던 URL 범위에서 전송
  • / : 웹 어플리케이션의 모든 URL 범위에서 전송

쿠키 maxAge

  • cookie.setMaxAge(초);
  • cookie.setMaxAge(0); : 바로 지움
  • cookie.setMaxAge(-1); : 세션 끝나면(브라우저 종료시) 지움

쿠키 동작 방식

    1. 생성 : 웹 서버측에서 생성함. 생성한 쿠키를 응답데이터의 헤더에 저장하여 웹 브라우저에 전송함
    1. 저장 : 웹 브라우저는 응답데이터에 포함된 쿠키를 쿠키 저장소에 보관함
    1. 전송 : 웹 브라우저는 요청이 있을 때마다 쿠키를 웹 서버에 전송함
  • response.addCookie(cookie); : 서버에서 쿠키 생성(오는 것)
  • request.getCookies(); : 클라이언트가 보낸 쿠키 읽음(가는 것)
  • getName() : 쿠키의 이름을 구함
  • getValue() : 쿠키의 값을 구함

쿠키 생성

makeCookie.jsp

  • 이름이 "name", 값이 "개똥이"인 쿠키 생성
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	//추가할 쿠키 정보를 담고 있는 Coockie 객체를 생성
	Cookie cookie = new Cookie("name", URLEncoder.encode("개똥이", "UTF-8"));
	
	//응답 데이터에 쿠키를 추가
	response.addCookie(cookie);
%>    
<!DOCTYPE html>
<html>
<head>
<title>쿠키 생성</title>
<script type="text/javascript">
	function fn_view() {
		location.href="/chapter09/viewCookies.jsp";
	}
</script>
</head>
<body>
<!-- 별도 유효 시간을 지정하지 않으면 웹 브라우저를 종료 시 쿠키도 함께 삭제됨 -->
<%=cookie.getName() %> 쿠키의 값 = <%=cookie.getValue()%>
<!-- <%=URLDecoder.decode(cookie.getValue(),"utf-8") %>을 하면 깨짐 없음 -->
	<input type="button" value="쿠키보기" onclick="fn_view()">
<!-- 아이디 저장하기 할 때 쿠키 사용함(유효시간 정해둠) -->	
	
</body>
</html>
  • 쿠키 값 디코딩 적용하지 않은 경우
  • 쿠키 값 디코딩 적용한 경우

쿠키 보기

viewCookies.jsp

  • makeCookie.jsp 에서 쿠키 보기 클릭시 viewCookies.jsp로 이동
  • 위에서 생성했던 name,개똥이 출력됨
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>쿠키 목록</title>
<script type="text/javascript">
	function fn_CRU(para) {
		if(para == "C") { //생성 페이지로 이동
			location.href = "/chapter09/makeCookie.jsp";
		
		}else if(para == "U") { //변경 페이지로 이동
			location.href = "/chapter09/modifyCookie.jsp";
		
		}else if(para =="D") { //삭제 페이지로 이동
			location.href = "/chapter09/deleteCookie.jsp";
		
		}else {
			alert("잘못된 명령입니다.");
		}
	}
</script>
</head>
<body>
	<h2>쿠키 목록</h2>
	<%
		
		Cookie[] cookies = request.getCookies();
		
		if(cookies != null && cookies.length > 0) {
			for(int i=0; i < cookies.length; i++) {
				//쿠키의 이름 = 값
				out.print(cookies[i].getName() + "=" +
						URLDecoder.decode(cookies[i].getValue(), "UTF-8") + "<br>");
			}
		}else {
			out.print("쿠키가 쿠키 저장소에 없습니다.");
		}
	%>
<input type="button" value="쿠키 생성" onclick="fn_CRU('C')">&nbsp;	
<input type="button" value="쿠키 변경" onclick="fn_CRU('U')">&nbsp;	
<input type="button" value="쿠키 삭제" onclick="fn_CRU('D')">&nbsp;	
</body>
</html>
  • 쿠키 생성화면에서 쿠키 보기 버튼 클릭시

쿠키 변경

modifyCookie.jsp

  • 기존에 생성했던 쿠키의 이름과 동일하게 생성하지만, 값을 다르게 생성함
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키 값 변경</title>
<script type="text/javascript">
	function fn_view() {
		location.href ="/chapter09/viewCookies.jsp";
	}
</script>
</head>
<body>
<!-- Cookie cookie = new Cookie("name", URLEncoder.encode("개똥이", "UTF-8")); -->
<%
	//이름이 name인 Cookie 객체를 새롭게 생성(기존에 생성했던 쿠키의 이름과 동일하게 생성하고 값만 다르게 함)
	Cookie cookie = new Cookie("name",URLEncoder.encode("김은대", "UTF-8"));
	//응답 헤더에 추가함 => name 쿠키의 값이 변경됨
	response.addCookie(cookie);
%>

name 쿠키의 값을 변경합니다.
<input type="button" value="쿠키목록" onclick="fn_view()">
</body>
</html>

쿠키 삭제

deleteCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie = new Cookie("name","개똥이");
	//Cookie 클래스는 쿠키를 삭제하는 기능이 없음
	//유효 시간을 0으로 지정함(setMaxAge()) => 초단위로 지정
	// 60 * 60 => 60초(1분) * 60 = 1시간
	//만약에 유효시간을 0초를 초과하여 정해놓으면 웹 브라우저를 종료해도 해당 시간만큼 
	//쿠키가 삭제되지 않고 웹 서버에 전송이 됨
	cookie.setMaxAge(0);
	//응답 헤더에 추가
	response.addCookie(cookie);
%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키 삭제</title>
<script type="text/javascript">
	function fn_view() {
		location.href="/chapter09/viewCookies.jsp";
	}
</script>
</head>
<body>
name 쿠키를 삭제합니다.
<input type="button" value="쿠키 목록" onclick="fn_view()">
</body>
</html>

Cookies Util

  • 쿠키로 로그인 수행 시 사용함
  • 쿠키를 <쿠키이름, 쿠키객체> 쌍 형태로 저장하는 맵 생성함
package util;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class Cookies {
	//쿠키를 <쿠키이름, Cookie객체> 쌍 형태로 저장하는 맵을 생성
	private Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
	
	//생성자 (객체 생성할 때 자동으로 쿠키 읽어옴)
	//request 안에는 파라미터로 전달되고 있는 Cookie들이 있음
	public Cookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		//각각의 Cookie 객체를 cookieMap에 저장
		if(cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
								//키(String)			, value(객체)
				cookieMap.put(cookies[i].getName(), cookies[i]);
			}
		}
	}
	
	//cookieMap에서 지정한 이름의 Cookie 객체를 구함
	//만약, 지정한 이름의 Cookie가 없으면 null을 리턴
	public Cookie getCookie(String name) {
		return cookieMap.get(name); //쿠키 객체 리턴
	}
	
	//지정한 이름의 쿠키 객체의 값을 반환
	public String getValue(String name) throws IOException {
		Cookie cookie = cookieMap.get(name);
		if(cookie == null) {
			return null;
		}
		return URLDecoder.decode(cookie.getValue(),"UTF-8");
	}
	
	//지정한 쿠키 이름의 Cookie가 있을 경우 true, 없을 경우 false를 리턴
	public boolean exists(String name) {
		return cookieMap.get(name)!= null;
	}
	
	//이름이 name이고, 값이 value인 Cookie 객체를 생성하여 리턴
	public static Cookie createCookie(String name, String value) throws IOException {
		return new Cookie(name, URLEncoder.encode(value, "UTF-8"));
	}
	
	
	//이름이 name이고, 값이 value, 경로가 path, 유효시간이 maxAge인 Cookie 객체를 생성하여 리턴
	public static Cookie createCookie(String name, String value, String path, int maxAge) throws IOException {
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		return cookie;
		
	}
	
	//이름이 name이고, 값이 value, 도메인이 domain, 경로가 path, 유효시간이 maxAge인 Cookie 객체를 생성하여 리턴
	public static Cookie createCookie(String name, String value, String domain, String path, int maxAge) throws IOException {
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
		cookie.setDomain(domain);
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		return cookie;
		
	}
}

Cookies Util 사용하기

1) 쿠키 생성

makeCookieUsingCookies.jsp

<%@page import="util.Cookies"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	response.addCookie(
			Cookies.createCookie("id", "ddit", "/", -1)
			// -1 : 웹 브라우저를 종료하면 사라짐 (default)
			);	
%>
<!DOCTYPE html>
<html>
<head>
<title>Cookies 클래스 사용 예</title>
</head>
<body>
<a href="/chapter09/readCookieUsingCookies.jsp">생성된 쿠키 정보 확인</a>

<!-- 
	쿠키 핵심 정리
	1. 쿠키 생성
		Cookie cookie = new Cookie("name", "a001");
		response.addCookie(cookie);
	
	2. 쿠키 사용
	1) 전체를 가져옴
		Cookie[] cookies = request.getCookies();
		cookies[0].getName();
		cookies[0].getValue();
	2) 하나를 가져옴
		Cookie cookie = new Cookie("name", "a001");
		cookie.getName();
		cookie.getValue();
 -->
</body>
</html>

2) 쿠키 읽기

readCookieUsingCookies.jsp

<%@page import="util.Cookies"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	//Cookie[] cookies = request.getCookies();
	Cookies cookies = new Cookies(request);
%>
<!DOCTYPE html>
<html>
<head>
<title>Cookies 클래스 사용</title>
</head>
<body>
<%=cookies.getValue("id") %>
</body>
</html>

쿠키 적용(로그인)

top.jsp에 로그인하기 추가(쿠키 사용)

  • 쿠키를 사용하여 로그인을 실행함
  • 로그인 되어 있지 않은 경우, 로그인 버튼 뜨고, 로그인 되어 있는 경우, 로그아웃 버튼 뜨게 함
  • 로그인 버튼 클릭 시, 오른쪽 화면에 로그인 할 수 있는 입력 창뜨고 로그인 수행함 => login.jsp로 이동 -> login2.jsp로 흐름 이동
  • 로그인 성공시, 쿠키에 적용된 아이디를 가져와 아이디님 환영합니다 출력함
  • 로그아웃 클릭시, logout.jsp로 이동

1) top.jsp

<%@page import="util.Cookies"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
상단 메뉴 : 
<a href="<%=request.getContextPath() %>/chapter07/layout.jsp"></a>&nbsp;
<a href="<%=request.getContextPath() %>/chapter07/info.jsp">정보</a>&nbsp;
&nbsp;&nbsp;&nbsp;
<%
	//cookieMap.put(cookies[i].getName(), cookies[i]);
	Cookies cookies = new Cookies(request);
	
	//id라는 이름의 쿠키가 존재하면 실행
	if(cookies.exists("id")) { //로그인 상태
		out.print(cookies.getValue("id") + "님 환영합니다.");
%>
		<input type="button" value="로그아웃" onclick="fn_logout()">
	<%}else { //로그인 안됨 %>
		<input type="button" value="로그인" onclick="fn_login()">
	<%}	%>
<script type="text/javascript">
	function fn_logout() {
		location.href = "/chapter09/logout.jsp";
	}
	
	function fn_login() {
		//layout.jsp를 복사한 후 내용부분에 chapter09/loginForm.jsp를 include
		location.href="/chapter07/login.jsp";
	}
</script>

2) login.jsp

  • layout.jsp 부분 중, 오른쪽 화면부분에 로그인 창 나오게 함
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>login</title>
</head>
<body>
	<table border="1" style="width: 100%;" cellpadding="0" cellspacing="0">
		<tr>
			<td colspan="2">
				<jsp:include page="/module/top.jsp"  flush="false" />  
			</td>
		</tr>
		<tr>
			<td style="width: 30%" valign="top">
				<jsp:include page="/module/left.jsp" />
			</td>
			<td>
				<!-- 내용 부분 : 시작 -->
				<jsp:include page="/chapter09/loginForm.jsp" flush="false"></jsp:include>
				<!-- 내용 부분 : 끝 -->
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<jsp:include page="/module/bottom.jsp" />
			</td>
		</tr>
	</table>
</body>
</html>

3) loginForm.jsp

  • 오른쪽 화면부분에 나오는 로그인 창(로그인 입력하는 화면(폼))
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>로그인 폼</title>
</head>
<body>
	<form action="<%= request.getContextPath() %>/chapter09/login.jsp" method="post">
		아이디 <input type="text" name="id" size="10"><br>
		비밀번호<input type="password" name="password" size="10"><br>
		<input type="submit" value="로그인">
	</form>
</body>
</html>
  • 로그인 입력창

4) login2.jsp

  • form 태그의 로그인 버튼 클릭 시 post방식으로 action값으로 이동
  • 실제 로그인 처리함
  • 임시로 아이디가 a001이고, 비밀번호가 1234인 경우만 쿠키 적용함
  • 쿠키 적용 시, Cookies Util을 사용함
  • 로그인 성공 시, 5초 카운트 다운 후 layout.jsp 화면으로 이동
    -로그인 실패 시, 로그인 실패 alert 띄운 후 전 단계 화면으로 이동함
<%@page import="util.Cookies"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String id = request.getParameter("id");
String password = 
	request.getParameter("password");
//아이디가 a001이면서 동시에 비밀번호가 1234인 경우 로그인 성공
if(id.equals("a001")&&password.equals("1234")){
// 	Cookie cookie = new Cookie("id",id);	
	response.addCookie(
			Cookies.createCookie("id", id, "/", -1)
	);	
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 성공</title>
</head>
<body>
	로그인에 성공했습니다.<br />
	<div class="count" style="font-size:1.2em;">5초 뒤에 메인화면으로 이동합니다.</div>
<script type="text/javascript">
const countDisplay = document.querySelector(".count");

//1초마다 countDown 함수를 실행
setInterval(countDown, 1000);
var time = 5;	//5초
function countDown(){
	if(time>0){	//5 4 3 2 1 
		time--;
		countDisplay.innerText = time + "초 뒤에 메인화면으로 이동합니다.";
	}else{	//0
		location.href="/chapter07/layout.jsp";
	}
}
</script>
</body>
</html>
<%
}else{	//로그인 실패 시
	out.print("<script>alert('로그인 실패');history.go(-1);</script>");
}
%>



  • 메인화면 넘어가기 전 초 세는 화면
  • 로그인 후 메인화면
  • 로그인 실패 시 alert
  • alert 후, 전 단계 화면으로 이동

5) logout.jsp

  • 이름이 "id"인 기존의 쿠키의 값을 ""(빈값)으로 생성하고, setMaxAge(0)을 하여 유효시간을 0으로 해줌 => 쿠키가 삭제되는 효과
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
	Cookie cookies = new Cookie("id", "");
	//유효시간을 0으로 설정 => 쿠키가 삭제되는 효과
	cookies.setMaxAge(0);
	cookies.setPath("/"); //생성할 때 "/"로 생성해서 삭제할 때도 해줘야됨
	response.addCookie(cookies);
%>
<!DOCTYPE html>
<html>
<head>
<title>로그아웃</title>
<script type="text/javascript">
	function fn_main() {
		var chk = confirm("메인화면으로 이동하시겠습니까?");
		if(chk) {
			location.href="/chapter07/layout.jsp"
		}
	}
</script>
</head>
<body>
로그아웃 되었습니다.<br>
<input type="button" value="메인" onclick="fn_main()">

</body>
</html>
  • 로그아웃 버튼 클릭 후, 메인 버튼 클릭시
  • 로그아웃 후 메인 화면 이동

0개의 댓글