본문 바로가기

개발/JSP

클라이언트와의 대화 1: 쿠기

01. 쿠키 사용하기

1.1 쿠기의 구성

  • 이름 : 각각의 쿠키를 구별하는 데 사용되는 이름
  • 값 : 쿠키의 이름과 관련된 값
  • 유효시간 : 쿠키의 유지 시간
  • 도메인 : 쿠키를 전송할 도메인
  • 경로 : 쿠키를 전송할 요청 경로
1.2 쿠키 생성하기

chap09\makeCookie.jsp
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import = "java.net.URLEncoder" %>
<%
	Cookie cookie = new Cookie("name", URLEncoder.encode("까망군", "euc-kr"));
	response.addCookie(cookie);
%>
<html>
<head><title>쿠키생성</title></head>
<body>
<%= cookie.getName() %> 쿠키의 값 = "<%= cookie.getValue() %>"
</body>
</html>
1.3 쿠키 값 읽어오기

chap09\viewCookies.jsp
<%@ 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(), "euc-kr") %><br />
<%
		}
	} else {
%>
쿠키가 존재하지 않습니다.
<%
	}
%>
</body>
</html>

1.4 쿠키 값 변경 및 쿠키 삭제하기

chap09\modifyCookie.jsp
<%@ 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프로그래밍", "euc-kr"));
				response.addCookie(cookie);
			}
		}
	}
%>
<html>
<head><title>값 변경</title></head>
<body>
name 쿠키의 값을 변경합니다.
</body>
</html>

chap09\deleteCookie.jsp
<%@ 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>

1.5 쿠키의 도메인

setDomain() : 생성된 쿠키가 전송될 수 있는 도메일을 지정한다.
  • .blackun.com : 점으로 시작하는 경우 관련 도메인에 모두 쿠키를 전송한다. 예를 들어, mail.blackun.com, www.blackun.com, javacan.blackun.com으로 모두 전송한다.
  • www.blackun.com : 특정 도메인에 대해서만 쿠키를 전송한다.

makeCookieWithDomain.jsp
<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page pageEncoding = "euc-kr" %>
<%@ page trimDirectiveWhitespaces = "true" %>
<%
	Cookie cookie1 = new Cookie("id", "blackun");
	cookie1.setDomain(".blackun.com");
	response.addCookie(cookie1);

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

	Cookie cookie3 = new Cookie("invalid", "invalidcookie");
	cookie3.setDomain("javacan.tistory.com");
	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>
*note : 도메인에 대한 예제는 localhost로는 테스트해 볼 수가 없다. 왜냐면 여러 도메인이 필요하기 때문이다. 그러므로 도메인과 관련된 예제를 실행해서 직접 결과를 보고 싶다면 별도의 서버를 활용할 수 있는 환경을 구축한 후 테스트하기 바란다. 또는 다음과 같이 hosts 파일에 직접 도메인을 추가해서 테스트 할 수도 있다.

127.0.0.1 somedomain.com
127.0.0.1 www.somedomain.com
127.0.0.1 otherdomain.com

참고로 hosts 파일은 윈도우즈의 경우는 c:\windows.system32\drivers\etc 디렉토리에 위치하며 리눅스의 경우는 \etc 디렉터리에 위치한다.


1.6 쿠키의 경로


쿠키는 도메인 뿐만 아니라 경로르 지정할 수 도 있다. Cookie 클래스의 setPath() 메서드를 사용하면 경로를 지정할 수 있게 된다.

1.7 쿠키의 유효 시간

쿠키의 유효 시간은 setMaxAge() 메서드를 사용하며, 0일 경우 쿠키는 브라우저 종료와 함께 바로 삭제된다. 쿠키의 유효시간으로 초를 입력한다.

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page pageEncoding = "euc-kr" %>
<%@ page trimDirectiveWhitespaces = "true" %>
<%
	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>

아이디 기억하기 기능의 구현 방법
로그인을 필요로 하는 사이트를 보면 아이디 기억하기 기능을 제공하는 곳이 있다. 이 아이디 기억하기 기능은 쿠키를 사용해서 구현한다. 먼저 사용자가 로그인에 성공하면 아이디를 값으로 저장하고 있는 쿠키의 유효 시간을 1달 정도로 여유롭게 잡아서 생성한다. 그러면 웹 브라우저를 닫더라도 유효 시간이 충분히 남아 있기 때문에 다음에 웹 브라우저를 열 때에 아이디를 저장하고 있는 쿠키를 사용할 수 있게 된다. 따라서 웹 프로그램은 아이디 쿠키가 존재할 경우 쿠키의 값을 로그인 폼에 출력해 주면 아이디 기억하기 기능이 구현된다.
로그인 상태 정보까지 동일한 방식으로 쿠키에 보관하면 자동 로그인 기능을 구현할 수도 있다. 

1.8 쿠키와 헤더

쿠키이름=쿠키값; Domain=도메인값; path=경로값; Expires=GMT형식의만료일시

02. 쿠키 처리를 위한 유틸리티 클래스 

좀 더 편리하게 쿠키를 사용할 수 있도록 도와주는 보조 유틸리티 클래스
package 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<String, Cookie> cookieMap = 
		new java.util.HashMap<String, Cookie>();

	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 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(), "euc-kr");
	}

	public boolean exists(String name){
		return cookieMap.get(name) != null;
	}
}
2.2 CookieBox 클래스를 이용한 쿠키 읽기

03. 쿠키를 사용한 로그인 유지

3.1 로그인 처리

\member\loginForm.jsp
<%@ page contentType="text/html; charset=euc-kr" %>
<%@ page pageEncoding="euc-kr" %>
<%@ page trimDirectiveWhitespaces = "true" %>
<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>

\member\login.jsp
<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page pageEncoding="euc-kr" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page import="util.CookieBox" %>
<%
	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>
<%
	}
%>
3.2 로그인 여부 판단

\member\loginCheck.jsp

<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page pageEncoding="euc-kr" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page import = "util.CookieBox" %>
<%
	CookieBox cookieBox = new CookieBox(request);
	boolean login = cookieBox.exists("LOGIN") && cookieBox.getValue("LOGIN").equals("SUCCESS");
%>
<html>
<head><title>로그인여부 검사</title></head>
<body>
<%
	if(login){
%>
아이디 "<%= cookieBox.getValue("ID") %>"로 로그인 한 상태
<%
	} else {
%>
로그인하지 않은 상태
<%
}
%>
</body>
</html>

3.3 로그아웃 처리

\member\logout.jsp

<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page pageEncoding="euc-kr" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page import = "util.CookieBox" %>
<%
	response.addCookie(
		CookieBox.createCookie("LOGIN", "", "/", 0)
	);
	response.addCookie(
		CookieBox.createCookie("ID", "", "/", 0)
	);
%>
<html>
<head><title>로그아웃</title></head>
<body>
로그아웃하였습니다.
</body>
</html>

.,..