금요일, 3월 29
Shadow

#010 클라이언트와의 대화1 : 쿠키

ㅇ 웹서버가 우 브라우저에 정보를 전달하는 방법
01. 쿠키 사용
쿠키란 : 웹 브라우저가 보관하고 있는 데이터로서 웹 서버에 요청을 보낼때 함꼐 전송된다. 웹서버와 웹 브라우저 양쪽에서 생성 할수 있으며, 웹 서버는 웹 브라우저가 전송한 쿠키를 사용하여 필요한 데이터를 읽어 올수 있다.
ㅇ 쿠키생성 단계 : 쿠키를 사용하기 위해서는 쿠키를 생성해야 한다.
ㅇ 쿠키저장단계 : 웹 브라우저는 응답데이터에 포하된 쿠키를 쿠키저장소에 보고나한다. 쿠키의 종류에 따라 메모리나 파일로 저장된다.
ㅇ 쿠키전송단계 : 웹 브라우저는 한번 저장된 쿠키를 매번 요청이 있을때 웹 서버에 전송한다. 웹서버는 웹 브라우저가 전송한 쿠키를 사용해서 핋요한 작업을 수행 할수있다.

– 웹브라우저는 쿠키가 삭제 되기 전까지 웹 서버에 쿠키를 전송한다. 지속적으로 유지해야 하는 정보는 쿠키를 사용해서 저장할수 있다.
1.1 쿠키의 구성
이름 : 각각의 쿠키 를 구별하는데 사용되는 이름
값 : 쿠키의 이름과 관련된 값
유효시간 : 쿠키의 유지 시간
도메인 : 쿠키를 전송할 도메인
경로 : 쿠키를 전송할 요청 경로

– 쿠키의 이름은 아스키 코드의 알파벳과 숫자만을 포함할수 있다.
– 콤마, 세미콜론, 공백등의 문자는 포함할수 없다.
– $ 로 시작할수 없다.

1.2 쿠키 생성하기
<%
Cookie cookie = new Cookie(“cookieName”, “cookieValue”);
response.addCookie(cookie);
%>

<% cookie.getName() %> 쿠키의 값 = “<%=cookie.getValue() %>

—–결과물——
cookieName 쿠키의 값 = cookievalue

cookie클래스가 제공하는 메소드

getName() : 쿠키의 이름을 구한다.
getValue() : 쿠키의 값을 구한다.
setValue(String value) : 쿠키의 값을 지정한다.
setDoimain(String pattern): 이 쿠키가 전송될 서버의 도메인을 지정한다.
getDomain() : 쿠키의 도메인을 구한다.
setPath(String uri) : 쿠키를 전송할 경로를 지정한다.
getPath() : 쿠키의 전송 경로를 궇ㄴ다.
setMaxAge(int expiry) : 쿠키의 유효시간을 초단위로 지정한다. 음수를 입력할경우 웹 브라우저를 닫을때 쿠키가 함께 삭제된다.
getMaxAge() : 쿠키의 유효시간을 구한다.

1.3 쿠키 값 읽어오기
Cookie[] cookies = request.getCookies();

1.4 쿠키 값 변경 및 쿠키 삭제하기
Cookie cookie = new Cookie(“name”, URLEncoder.encode(“새로운 값”, “euc-kr”));
response.addCookie(cookie);

쿠키 삭제 ————-
Cookie cookie = newCookie(name, value);
cookie.setMaxAge(0);
response.addCookie(cookie);

1.5 쿠키의 도메인
Cookie cookie1 = newCookie(“id”, “starstory”);
cookie1.setDomain(“.starstory”);
response.addCookie(cookie1);

1.6 쿠키의 경로
쿠키는 도메인 뿐만아니라 경로를 지정할 수도 있다.
Cookie cookie1 = newCookie(“path1”,URLEncoder.encode(“경로:/enter”, “euc-kr”));
cookie1.setPath(“/enter”);
respnse.addCookie(cookie1);

1.7 쿠키의 유효시간
쿠키는 유효시간을 갖고 이씅며 유효시간을 지정하지 않은 경우 웹 브라우저를 닫으면 쿠키는 자옫으로 삭제되며, 이후 웹 브라우저를 실행할때에 지워진 쿠키를 사용할수 없게 된다.
Cookie cookie = newCookie(name, value);
cookie.setMaxAge(60 *60); = 60초 * 60 = 1시간
response.addCookie(cookie);

1.8 쿠키와 헤더
쿠키는 응답 헤더 형태로 웹 브라우저에 전달되기 때문에 쿠키 역시 출력 버퍼가 플러시 된 이후에는 새롭게 추가 할수 없다. 따라서 쿠키의 추가 및 변경 작업은 반드시 출력버퍼가 플러시 되기 전에 처리해 주어야 한다.

02. 쿠리 처리를 위한 유틸리티 클래스
* 쿠키생성
– Cookie클래스의 생성자를 사용하는 대신 CookieBox.createCookie()메서드를 사용하면 된다.
Cookie cookie1 = Cookiebox.createCookie(“name”,”홍길동”);
Cookie cookie2 = Cookiebox.createCookie(“name”,”홍길동”,”path1″,-1);
Cookie cookie3 = Cookiebox.createCookie(“id”,”jsp”,”.starstory.us”,”/”,60);

————————————–CookieBox클래스를 사용하게 되면
Cookie cookie= new Cookie(“id”, URLEncoder.encode(value));
Cookie.setDomain(“.starstory.us”);
cookie.setPath(“/”);
cookie.setMaxAge(60);
—————————————다음과 같은 코드를 사용하면 더 간결하게 쿠키를 추가 할수 있다.
response.addCookie(CookieUtil.createCookie(name, value));
response.addCookie(CookieUtil.createCookie(“id”,”starstory”,”/chap09″,-1));
———————- 한줄로 끝
2.2 CookieBox 클래스를 이용한 쿠키 읽기
//쿠키가 존재하는지 확인
if(cookieBox.exists(“name”)){
//Cookie 클래스로 사용할 경우 getCookie() 메서드 사ㅛㅇ
Cookie cookie = cookieBox.getCookie(“name”);
}
if(cookieBox.exists(“id”)){
//값만 사용할 경우 getValue() 메서드 사용
String value = cookieBox.getValue(“name”);
}

03. 쿠키를 사용한 로그인 유지
1. 로그인을 하면 관련 쿠키를 생성한다.
2. 관련쿠키가 존재하면 로그인한 상태라고 판단한다.
3. 로그아웃을 하면 고나련 쿠키를 삭제한다.

3.1 로그인 처리
————login.jsp
<%
String id = request.getparameter(“id”);
String password = request.getParameter(“password”);

response.addcookie( CookieBox.createCookie(“LOGIN”,”SUCCESS”, “/”, -1));
response.addCookie(CookieBox.createCookie(“ID”,id,”/”,-1));
%>
3.2 로그인 판단여부
<%
boolean login = cookieBox.exists(“LOGIN”) && cookieBox.getvalue(“LOGIN”).equals(“SUCCESS”);
%>

<%= cookieBox.getValue(“ID”) %>”로 로그인 한 상태
3.3 로그아웃 처리
<% response.addCookie(CookieBox.createCookie(“LOGIN”,”‘””/”,0));
<% response.addCookie(CookieBox.createCookie(“ID”,”‘””/”,0));

:::쿠키생성:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLEncoder” %>
<%
Cookie cookie = new Cookie(“name”, URLEncoder.encode(“최범균”));
response.addCookie(cookie);
%>
<html>
<head><title>쿠키생성</title></head>
<body>

<%= cookie.getName() %> 쿠키의 값 = “<%= cookie.getValue() %>”

</body>
</html>

 

:::쿠키 뷰:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLDecoder” %>
<html>
<head><title>쿠키목록</title></head>
<body>
쿠키 목록<br>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (int i = 0 ; i < cookies.length ; i++) {
%>
<%= cookies[i].getName() %> =
<%= URLDecoder.decode(cookies[i].getValue()) %><br>
<%
}
} else {
%>
쿠키가 존재하지 않습니다.
<%
}
%>
</body>
</html>

 
:::쿠키값 변경:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLEncoder” %>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (int i = 0 ; i < cookies.length ; i++) {
if (cookies[i].getName().equals(“name”)) {
Cookie cookie = new Cookie(“name”,
URLEncoder.encode(“JSP프로그래밍”));
response.addCookie(cookie);
//cookies[i].setValue(URLEncoder.encode(“자바와 JSP”));
//response.addCookie(cookies[i]);
}
}
}
%>
<html>
<head><title>값 변경</title></head>
<body>
name 쿠키의 값을 변경합니다.
</body>
</html>

 
:::쿠키 삭제:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLEncoder” %>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (int i = 0 ; i < cookies.length ; i++) {
if (cookies[i].getName().equals(“name”)) {
Cookie cookie = new Cookie(“name”, “”);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
%>
<html>
<head><title>쿠키 삭제</title></head>
<body>
name 쿠키를 삭제합니다.
</body>
</html>

 
:::쿠키의 도메인:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLEncoder” %>
<%
Cookie cookie1 = new Cookie(“id”, “madvirus”);
cookie1.setDomain(“.madvirus.net”);
response.addCookie(cookie1);

Cookie cookie2 = new Cookie(“only”, “onlycookie”);
response.addCookie(cookie2);

Cookie cookie3 = new Cookie(“invalid”, “invalidcookie”);
cookie3.setDomain(“javateam.korea.ac.kr”);
response.addCookie(cookie3);
%>
<html>
<head><title>쿠키생성</title></head>
<body>

다음과 같이 쿠키를 생성했습니다.<br>
<%= cookie1.getName() %>=<%= cookie1.getValue() %>
[<%= cookie1.getDomain() %>]
<br>
<%= cookie2.getName() %>=<%= cookie2.getValue() %>
[<%= cookie2.getDomain() %>]
<br>
<%= cookie3.getName() %>=<%= cookie3.getValue() %>
[<%= cookie3.getDomain() %>]

</body>
</html>

 

:::쿠키의 경로:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “java.net.URLEncoder” %>
<%
Cookie cookie1 = new Cookie(“path1”,
URLEncoder.encode(“경로:/chap09/path1”));
cookie1.setPath(“/chap09/path1”);
response.addCookie(cookie1);

Cookie cookie2 = new Cookie(“path2”,
URLEncoder.encode(“경로:”));
response.addCookie(cookie2);

Cookie cookie3 = new Cookie(“path3”,
URLEncoder.encode(“경로:/”));
cookie3.setPath(“/”);
response.addCookie(cookie3);

Cookie cookie4 = new Cookie(“path4”,
URLEncoder.encode(“경로:/chap09/path2”));
cookie4.setPath(“/chap09/path2”);
response.addCookie(cookie4);
%>

<html>
<head><title>쿠키 경로 지정</title></head>
<body>

다음과 같이 쿠키를 생성했습니다.<br>
<%= cookie1.getName() %>=<%= cookie1.getValue() %>
[<%= cookie1.getPath() %>]
<br>
<%= cookie2.getName() %>=<%= cookie2.getValue() %>
[<%= cookie2.getPath() %>]
<br>
<%= cookie3.getName() %>=<%= cookie3.getValue() %>
[<%= cookie3.getPath() %>]
<br>
<%= cookie4.getName() %>=<%= cookie4.getValue() %>
[<%= cookie4.getPath() %>]

</body>
</html>

 

:::쿠키의 유효시간 설정:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%
Cookie cookie = new Cookie(“oneh”, “1time”);
cookie.setMaxAge(60 * 60); // 60초(1분) * 60 = 1시간
response.addCookie(cookie);
%>
<html>
<head><title>쿠키유효시간설정</title></head>
<body>

유효시간이 1시간인 oneh 쿠키 생성.

</body>
</html>

 

 
:::쿠키생성클래스:::(.java)
//package jsp.util;

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

public class CookieBox {

private Map cookieMap = new java.util.HashMap();

public CookieBox(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0 ; i < cookies.length ; i++) {
cookieMap.put(cookies[i].getName(), cookies[i]);
}
}
}

public static Cookie createCookie(String name, String value)
throws IOException {
return new Cookie(name, URLEncoder.encode(value, “euc-kr”));
}

public static Cookie createCookie(
String name, String value, String path, int maxAge)
throws IOException {
Cookie cookie = new Cookie(name,
URLEncoder.encode(value, “euc-kr”));
cookie.setPath(path);
cookie.setMaxAge(maxAge);
return 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, “euc-kr”));
cookie.setDomain(domain);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
return cookie;
}

public Cookie getCookie(String name) {
return (Cookie)cookieMap.get(name);
}

public String getValue(String name) throws IOException {
Cookie cookie = (Cookie)cookieMap.get(name);
if (cookie == null) return null;
return URLDecoder.decode(cookie.getValue(), “euc-kr”);
}

public boolean exists(String name) {
return cookieMap.get(name) != null;
}
}

 

 

:::클래스를 이용한 쿠키생성:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “jsp.util.Cookie!Box” %>
<%
response.addCookie(CookieBox.createCookie(“name”, “최범균”));
response.addCookie(
CookieBox.createCookie(“id”, “madvirus”, “/chap09”, -1));
%>
<html>
<head><title>CookieBox사용예</title></head>
<body>

CookieBox를 사용하여 쿠키 생성

</body>
</html>

 
:::클래스를 이용한 쿠키읽기:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “jsp.util.Cookie!Box” %>
<%
CookieBox cookieBox = new CookieBox(request);
%>
<html>
<head><title>Cookie 사용</title></head>
<body>

name 쿠키 = <%= cookieBox.getValue(“name”) %> <br>
<%  if (cookieBox.exists(“id”)) { %>
id 쿠키 = <%= cookieBox.getValue(“id”) %> <br>
<%  }  %>
</body>
</html>

 
:::로그인폼:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<html>
<head><title>로그인폼</title></head>
<body>

<form action=”<%= request.getContextPath() %>/member/login.jsp”
method=”post”>
아이디 <input type=”text” name=”id” size=”10″>
암호 <input type=”password” name=”password” size=”10″>
<input type=”submit” value=”로그인”>
</form>

</body>
</html>

 

:::로그인:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “jsp.util.Cookie!Box” %>
<%
String id = request.getParameter(“id”);
String password = request.getParameter(“password”);

if (id.equals(password)) {
// ID와 암호가 같으면 로그인에 성공한 것으로 판단.
response.addCookie(
CookieBox.createCookie(“LOGIN”, “SUCCESS”, “/”, -1)
);
response.addCookie(
CookieBox.createCookie(“ID”, id, “/”, -1)
);
%>
<html>
<head><title>로그인성공</title></head>
<body>

로그인에 성공했습니다.

</body>
</html>
<%
} else { // 로그인 실패시
%>
<script>
alert!(“로그인에 실패하였습니다.”);
history.go(-1);
</script>
<%
}
%>

 
:::로그아웃:::
<%@ page contentType = “text/html; charset=euc-kr” %>
<%@ page import! = “jsp.util.Cookie!Box” %>
<%
response.addCookie(
CookieBox.createCookie(“LOGIN”, “”, “/”, 0)
);
response.addCookie(
CookieBox.createCookie(“ID”, “”, “/”, 0)
);
%>
<html>
<head><title>로그아웃</title></head>
<body>

로그아웃하였습니다.

</body>
</html>

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.