쿠키 다루기
var allCookies = document.cookie
위 코드는 현재 문서 객체가 접근할 수 있는 모든 쿠키를 얻는다.
document.cookie = newCookie;
위 코드는 새로운 쿠키를 추가한다.
(추가한다고 document.cookie += newCookie;처럼 사용하지 않는다)
쿠키를 다루기 위한 사용자 정의 함수
아래 createCookie(), readCookie(), deleteCookie() 함수는 각각 쿠키를 굽고 쿠키를 읽고 쿠키를 삭제한다.
쿠키를 굽는 createCookie() 함수는 쿠키 이름=쿠키값; 파기 날짜; 형태의 문자열을 생성한다.
(이 경우 도메인, 경로, 보안은 디폴트 값이 적용된다)
function createCookie(name, value, days) {
var newCookie = name + "=" + escape(value);
if (days) {
var expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
newCookie += "; expires=" + expires.toGMTString();
}
document.cookie = newCookie;
}
function readCookie(name) {
var allCookies = document.cookie;
var beginIndex = allCookies.indexOf(" " + name + "=");
if (beginIndex === -1) {
beginIndex = allCookies.indexOf(name + "=");
}
if (beginIndex === -1) {
return null;
} else {
beginIndex = allCookies.indexOf("=", beginIndex) + 1;
var endIndex = allCookies.indexOf(";", beginIndex);
if (endIndex === -1) {
endIndex = allCookies.length;
}
return unescape(allCookies.substring(beginIndex, endIndex));
}
}
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
사용자 정의 함수를 이용해서 게시판에 적용할 수 있는 예제를 만들었다.
예제에서 사용자는 게시판 목록의 페이지당 레코드 수를 쿠키에 저장할 수 있다.
(구글 크롬은 로컬에서 생산한 쿠키를 저장하지 않기에, 로컬 테스트를 하려면 다른 브라우저를 사용하라)
Test.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>자바스크립트 쿠키 테스트</title>
<script>
window.onload = initPage;
function initPage() {
var selectBox = document.getElementById("numPerPage");
selectBox.onchange = setNumPerPage;
var delNumPerPageBtn = document.getElementById("del-numPerPage-btn");
delNumPerPageBtn.onclick = delNumPerPageCookie;
}
function setNumPerPage() {
var selectBox = document.getElementById("numPerPage");
var numPerPage = selectBox.value;
createCookie('numPerPage', numPerPage, '100');
showCookie();
}
function showCookie() {
var numPerPage = readCookie("numPerPage");
var div = document.getElementById('show-npp-div');
if(numPerPage) {
div.innerHTML = numPerPage;
} else {
div.innerHTML = '쿠키가 없습니다!';
}
}
function delNumPerPageCookie() {
deleteCookie("numPerPage");
showCookie();
}
function createCookie(name, value, days) {
var newCookie = name + "=" + escape(value);
if (days) {
var expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
newCookie += "; expires=" + expires.toGMTString();
}
document.cookie = newCookie;
}
function readCookie(name) {
var allCookies = document.cookie;
if (!allCookies) {
return null;
}
var beginIndex = allCookies.indexOf(" " + name + "=");
if (beginIndex === -1) {
beginIndex = allCookies.indexOf(name + "=");
}
if (beginIndex === -1) {
return null;
} else {
beginIndex = allCookies.indexOf("=", beginIndex) + 1;
var endIndex = allCookies.indexOf(";", beginIndex);
if (endIndex === -1) {
endIndex = allCookies.length;
}
return unescape(allCookies.substring(beginIndex, endIndex));
}
}
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
</script>
</head>
<body>
<div>
<select id="numPerPage">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
<input type="button" id="del-numPerPage-btn" value="numPerPage 쿠키 삭제" />
</div>
<div id="show-npp-div"></div>
</body>
</html>
setNumPerPage() 함수는 100일간 유지되는 numPerPage 쿠키를 굽는다.
function setNumPerPage() {
var selectBox = document.getElementById("numPerPage");
var numPerPage = selectBox.value;
createCookie('numPerPage', numPerPage, '100');
}
numPerPage 쿠키가 구워지면 서버 측 코드는 다음처럼 쿠키를 얻을 수 있다.
int numPerPage = 10;// 디폴트 레코드 수
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
if (name.equals("numPerPage")) {
numPerPage = Integer.parseInt(cookies[i].getValue());
break;
}
}
}
참고
