본문 바로가기
STUDY/JSP

쿠키(cookie)

by Anne of Green Galbes 2019. 2. 28.

쿠키(cookie)

○ 사용자의 컴퓨터에 저장

○ 웹 브라우저가 보관하고 있는 데이터로, 웹 서버에 요청을 보낼때 쿠키를 헤더에 담아 전송

○ 웹 서버는 웹 브라우저가 전송한 쿠키를 사용해서 필요한 데이터를 읽을 수 있음


1. 쿠키 동작 방식

○ 쿠키 생성 단계 : JSP에서 쿠키는 서버측에서 생성.

  생성한 쿠키를 응답 데이터의 헤더에 저장해서 웹 브라우저에 전송

○ 쿠키 저장 단계 : 응답 데이터에 포함된 쿠키를 쿠키 저장소에 보관

○ 쿠키 전송 단계 : 웹 브라우저는 저장한쿠키를 요청이 있을 떄마다 웹 서버에 전송.

                             웹 서버는 웹 브라우저가 전송한 쿠키를 사용해서 필요한 작업을 수행

○ 쿠키 저장소 확인 : 인터넷 옵션 > 설정 > 파일 보기


○ 저장된 쿠키 확인


2. 쿠키 구성

: 각각의 쿠키를 구별하는 데 사용되는 이름

: 쿠키의 이름과 관련된 값

○ 유효시간 : 쿠키의 유지 시간

○ 도메인 : 쿠키를 전송할 도메인

○ 경로 : 쿠키를 전송할 요청 경로


3-1. 쿠키 생성

Cookie cookie = new Cookie(“쿠키이름”,”쿠키값”)

response.addCookie(cookie);

○ c1.jsp

   - 한글은 인코딩 작업을 해야한다.

<%@page import="java.net.URLEncoder"%>

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

//쿠키의 데이터를 저장

Cookie c1 = new Cookie("name","suzi");

Cookie c2 = new Cookie("age","25");

Cookie c3 = new Cookie("addr",URLEncoder.encode("서울","UTF-8"));

//클라이언트에게 쿠키 전달

response.addCookie(c1);

response.addCookie(c2);

response.addCookie(c3);

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>


3-2. 쿠키 값 읽기

request.getCookies();

쿠키는 배열로 받는다.

○ c2.jsp

   - 읽어온 쿠키를 보여줄때는 풀어서 보여줘야한다.

      → 그대로 출력하면 해시코드가 출력

   - 인코딩을 하여 값을 보냈기 때문에, 디코딩하여 받아야한다.

<%@page import="java.net.URLDecoder"%>

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

//쿠키 받아오기

Cookie[] c = request.getCookies();

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

if(c!=null){

for(Cookie cc : c){

out.print("쿠키이름:");

out.print(cc.getName());

out.print(", 쿠키값:");

String str = cc.getValue();

if(cc.getName().equals("addr")){

str = URLDecoder.decode(str,"UTF-8");

}

out.print(str + "<br/>");

}

}

%>

</body>

</html>


3-3. 결과

○ c1.jsp

○ c2.jsp


4-1. 쿠키 값 변경

○ 쿠키 유호기간 지정 

   cookie.setMaxAge(초);

   0 : 쿠키가 바로 지워짐

   -1 : 쿠키가 끝가지 유지

○ 쿠키 접근 지정

   cookie.setPath(경로);

   cookie.setPath("/") : 프로젝트 내 어디서나 접근 가능

○ c3.jsp

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

Cookie c1 = new Cookie("name","shin");

Cookie c2 = new Cookie("age","30");

Cookie c3 = new Cookie("addr","Pusan");

Cookie c4 = new Cookie("tel","010-1234-1234");

//쿠키 유효기간 지정

c1.setMaxAge(0);

c2.setMaxAge(-1);

c3.setMaxAge(10); //10초후 삭제

//c2.setPath("/");         //내 프로젝트 어디서나 접근 가능

//c4.setPath("/board"); //board에서만 접근이 가능 → getName, getValue등 사용 가능

response.addCookie(c1);

response.addCookie(c2);

response.addCookie(c3);

response.addCookie(c4);

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

<a href="c4.jsp">확인</a>

</body>

</html>



4-2. 쿠키 값 삭제 및 변경 확인

○ 쿠기 값 삭제

   쿠키가 넘어오는 시간과 동시에 쿠키 값을 null로 다시 생성

   Cookie cookie = new Cookie("쿠키이름",null);

   response.addCookie(cookie);

○ c4.jsp

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

//쿠키 지우기

Cookie c4 = new Cookie("tel",null);

response.addCookie(c4);

Cookie[] ck = request.getCookies();

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

if(ck!=null){

for(Cookie c : ck){

out.print("쿠키이름:");

out.print(c.getName());

out.print(", 쿠키값:");

out.print(c.getValue() + "<br/>");

}

}

%>

</body>

</html>


4-3. 결과

○ c3.jsp


○ c4.jsp

  - name : 처음부터 보이지 않는다. → 유지기간을 0으로 했기 때문

  - age : 계속 보인다.

  - addr : 처음에는 보인다.

  - tel : 처음에는 보인다.


○ c4.jsp

  - 10초가 지난 후 

  - addr : 쿠키를 삭제하여 보이지 않는다.

  - tel : 쿠키값을 null로 하여 쿠키값이 보이지 않는다.


5. 쿠키관련 예제

○ 관련 파일 확인



① 쿠키값 화면에 띄어주기

○ 오늘 본 상품 목록 생성

○ shop.jsp

<%@page import="java.net.URLDecoder"%>

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

Cookie[] ck = request.getCookies();

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

<table border="1" width="400" cellpadding="0" cellspacing="0" >

<tr>

<th>상품명</th>

<th>상품가격</th>

</tr>

<tr align="center">

<td><a href="p1.jsp">냉장고</a></td>

<td>1000</td>

</tr>

<tr align="center">

<td><a href="p2.jsp">세탁기</a></td>

<td>2000</td>

</tr>

<tr align="center">

<td><a href="p3.jsp">LEDTV</a></td>

<td>3000</td>

</tr>

</table>

<br/>

<hr align="left" width="400" color="red">

<b>오늘 본 상품 목록</b><br/>

<%

if(ck!=null){

for(int i=ck.length-1;i>=0;i--){

if(ck[i].getName().indexOf("productName")!=-1){

String str = (URLDecoder.decode(ck[i].getValue(),"UTF-8"));

%>

<img alt="<%=str %>" height="150" src="./image/<%=str%>.jpg"><%=str %><br/>

<%

}

}

}

%>

</body>

</html>

○ p1.jsp

- p2.jsp / p3.jsp 다 같은 형식

- 쿠키를 생성 후 보냄

<%@page import="java.net.URLEncoder"%>

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

//쿠키를 만드는 곳

Cookie c = new Cookie("productName1", URLEncoder.encode("냉장고","UTF-8"));

c.setMaxAge(10);

response.addCookie(c);

%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

잘얼어 냉장고<br/>

<img alt="냉장고" src="./image/냉장고.jpg"><br/>

<a href="shop.jsp">돌아가기</a>

</body>

</html>


② 결과

○ shop.jsp


○ p3.jsp

   - 쿠키 생성 후 쿠키를 보낸다.


○ shop.jsp

   - 쿠키를 받아서 화면에 출력


댓글