본문으로 바로가기

13.쿠키

category 프로그래밍/jsp 2017. 10. 18. 23:41

쿠키란


웹브라우저에서 서버로 어떤 데이터를 요청 하면, 서버측에서는 알맞은 로직을 수행한 후 데이터를 웹브라우저에 응답 합니다. 그리고, 서버는 웹브라우저와의 관계를 종료합니다. 이렇게, 웹브라우저에 응답 후 관계를 끊는 것은 http프로토콜의 특징 입니다.

연결이 끊겼을 때 어떤 정보를 지속적으로 유지하기 위한 수단으로 쿠키라는 방식을 사용 합니다.

쿠키는 서버에서 생성하여, 서버가 아닌 클라이언트측에 특정 정보를 저장 합니다. 그리고 서버에 요청 할 때 마다 쿠키의 속성값을 참조 또는 변경 할 수 있습니다.

쿠키는 4kb로 용량이 제한적이며, 300개까지 데이터 정보를 가질 수 있습니다.



예를들어서 id와 비밀번호를 입력하여 서버에서 통과가 되어 response되었다고 가정하자.

웹브라우저를 새로 열게 되면 id와 비밀번호를 또 입력해야 하는데 

이를 방지하기 위해서 쿠키를 생성하여 요청할때마다 저장된정보를 다시 서버에서 클라이언트로 보내주는 역할을 한다. 


쿠키 문법


쿠키는 서버에서 생성되고, 클라이언트측에 전송되어 저장된다고 하였습니다.

쿠키 생성 방법 및 관련 메소드들을 살펴 봅니다.


      쿠키 생성 -------------> 속성 설정-------------> response객체에 쿠키 탑재

id, pw, name 등            response.addcoukie



주요 메소드


setMaxAge() : 쿠키 유효기간을 설정 합니다.

setpath() : 쿠키사용의 유효 렉토리를 설정 합니다.

setValue() : 쿠키의 값을 설정 합니다.

setVersion() : 쿠키 버전을 설정 합니다.

getMaxAge() : 쿠키 유효기간 정보를 얻습니다.

getName() : 쿠키 이름을 얻습니다.

getPath() : 쿠키사용의 유효 디렉토리 정보를 얻습니다.

getValue() : 쿠키의 값을 얻습니다.

getVersion() : 쿠키 버전을 얻습니다.



<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>



<%  쿠키 생성                               이름         값

Cookie cookie = new Cookie("cookieN", "cookieV"); Cookie 클래스의 객체를 만들어야 한다. 

cookie.setMaxAge(60*60); //1시간동안 유지

response.addCookie(cookie); 쿠키를 추가한다. 웹브라우저로

%>

<a href="cookieget.jsp">cookie get</a>  < a href = "이동할 페이지 주소">  제목</a> cokieget으로 쿠키를 넘긴다. 

</body>

</html>




%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

   쿠키 사용법

<%

Cookie[] cookies = request.getCookies(); 리퀘스트로 쿠키 배열로 받는다(모든 쿠키값을 가져옴 서버입장에서)

for(int i=0; i<cookies.length; i++) { for문을 이용하여 출력

String str = cookies[i].getName(); for문을 이용하여 0번째 원소부터 그 길이만큼 쿠키를 가져온다. 

if(str.equals("cookieN")) { cookieN이 같다면

out.println( " name : " + cookies[i].getName() + "<br />");

out.println( value : " + cookies[i].getValue() + "<br />");

out.println("=====================<br />");

}

}

%>


<a href="cookiedel.jsp">cookie delete</a> 쿠키 삭제


</body>

</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>


<%

Cookie[] cookies = request.getCookies();리퀘스트로 쿠키를 받는다

for(int i=0; i<cookies.length; i++) {

String str = cookies[i].getName();

if(str.equals("cookieN")) {

out.println("name : " + cookies[i].getName() + "<br />");

cookies[i].setMaxAge(0); 유효기간을 0을 주어서 쿠키를 삭제한다. 

response.addCookie(cookies[i]);

}

}

%>

<a href="cookietest.jsp">쿠키확인</a>


</body>

</html>



<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>


<%

Cookie[] cookies = request.getCookies();

if(cookies != null) { // id와 pw값을 지웠으므로 null이 된다. 만약 아니라면 name과 value를 출력하라는 의미

for(int i=0; i<cookies.length; i++){

out.println(cookies[i].getName() + "<br />");  모든 네임과 값을 출력 여기어 cookieN이 있으면 안됨

out.println(cookies[i].getValue() + "<br />");

}

}

%>


</body>

</html>